From 1f3eb9fa158be6607e09f571d74ff32b0ed393c9 Mon Sep 17 00:00:00 2001 From: Anderson Herzogenrath da Costa Date: Tue, 7 May 2024 09:48:40 -0400 Subject: [PATCH] use functools cache to improve performance --- fpdf/fonts.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/fpdf/fonts.py b/fpdf/fonts.py index 6d93a796d..c0eaa6909 100644 --- a/fpdf/fonts.py +++ b/fpdf/fonts.py @@ -12,6 +12,7 @@ from bisect import bisect_left from collections import defaultdict from dataclasses import dataclass, replace +from functools import lru_cache from typing import List, Optional, Tuple, Union from fontTools import ttLib @@ -449,8 +450,6 @@ def __init__(self, font: TTFFont, identities: List[int]): glyph = self.get_glyph(unicode=x) if glyph: self._char_id_per_glyph[glyph] = int(x) - # This is a cache to speed things up: - self._char_id_per_unicode = {} def __repr__(self): return ( @@ -465,10 +464,8 @@ def items(self): for glyph, char_id in self._char_id_per_glyph.items(): yield glyph, char_id + @lru_cache(maxsize=128) def pick(self, unicode: int): - cache_hit = self._char_id_per_unicode.get(unicode) - if cache_hit: - return cache_hit glyph = self.get_glyph(unicode=unicode) if glyph is None and unicode not in self.font.missing_glyphs: self.font.missing_glyphs.append(unicode) @@ -484,10 +481,9 @@ def pick_glyph(self, glyph): char_id = self._next self._char_id_per_glyph[glyph] = char_id self._next += 1 - # Fill cache: - self._char_id_per_unicode[glyph.unicode] = char_id return char_id + @lru_cache(maxsize=128) def get_glyph( self, glyph=None, unicode=None, glyph_name=None, glyph_width=None ) -> Glyph: