Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of cell_length #2061

Merged
merged 4 commits into from Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Changed

- Improve performance of cell_length https://github.com/Textualize/rich/pull/2061

## [12.0.1] - 2022-03-14

### Fixed
Expand Down
24 changes: 9 additions & 15 deletions rich/cells.py
@@ -1,5 +1,5 @@
from functools import lru_cache
import re
from functools import lru_cache
from typing import Dict, List

from ._cell_widths import CELL_WIDTHS
Expand All @@ -18,17 +18,14 @@ def cell_len(text: str, _cache: Dict[str, int] = LRUCache(1024 * 4)) -> int:
Returns:
int: Get the number of cells required to display text.
"""

if _is_single_cell_widths(text):
return len(text)
else:
cached_result = _cache.get(text, None)
if cached_result is not None:
return cached_result
_get_size = get_character_cell_size
total_size = sum(_get_size(character) for character in text)
if len(text) <= 64:
_cache[text] = total_size
cached_result = _cache.get(text, None)
if cached_result is not None:
return cached_result

_get_size = get_character_cell_size
total_size = sum(_get_size(character) for character in text)
if len(text) <= 512:
_cache[text] = total_size
return total_size


Expand All @@ -42,9 +39,6 @@ def get_character_cell_size(character: str) -> int:
Returns:
int: Number of cells (0, 1 or 2) occupied by that character.
"""
if _is_single_cell_widths(character):
return 1

return _get_codepoint_cell_size(ord(character))


Expand Down