From eed6cbff5811ef2db0330c1653eaf03975030eee Mon Sep 17 00:00:00 2001 From: Darren Burns Date: Mon, 14 Mar 2022 14:22:56 +0000 Subject: [PATCH 1/2] Remove restriction on lenght of cell_len cache keys, dont use regex --- rich/cells.py | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/rich/cells.py b/rich/cells.py index e824ea2a6..247fae7c2 100644 --- a/rich/cells.py +++ b/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 @@ -18,17 +18,13 @@ def cell_len(text: str, _cache: Dict[str, int] = LRUCache(1024 * 4)) -> int: Returns: int: Get the number of cells required to display text. """ + cached_result = _cache.get(text, None) + if cached_result is not None: + return cached_result - 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 + _get_size = get_character_cell_size + total_size = sum(_get_size(character) for character in text) + _cache[text] = total_size return total_size @@ -42,9 +38,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)) From c4cf06d205e443bdbc4fc66b6836a9bf13e5cf21 Mon Sep 17 00:00:00 2001 From: Darren Burns Date: Mon, 14 Mar 2022 16:29:32 +0000 Subject: [PATCH 2/2] Limit cache key in cell_len to 512 --- CHANGELOG.md | 6 ++++++ rich/cells.py | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 395a4d30d..9f1a7e64f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/rich/cells.py b/rich/cells.py index 247fae7c2..dd4d5e9d0 100644 --- a/rich/cells.py +++ b/rich/cells.py @@ -24,7 +24,8 @@ def cell_len(text: str, _cache: Dict[str, int] = LRUCache(1024 * 4)) -> int: _get_size = get_character_cell_size total_size = sum(_get_size(character) for character in text) - _cache[text] = total_size + if len(text) <= 512: + _cache[text] = total_size return total_size