Skip to content

Commit

Permalink
Merge pull request #2061 from Textualize/perf-cell-len-regex
Browse files Browse the repository at this point in the history
Improve performance of cell_length
  • Loading branch information
willmcgugan committed Mar 15, 2022
2 parents 51121fe + c4cf06d commit 1b69bfe
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 15 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 1b69bfe

Please sign in to comment.