From 1ad0040d14234a2cc4e560aeaca22b9ca25793d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20Lef=C3=A8vre?= Date: Tue, 6 Jun 2023 10:15:01 +0000 Subject: [PATCH] [FIX] rendering: cache text width MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Computing the text width is expensive, so we cache it Task 3354651 closes odoo/o-spreadsheet#2558 Signed-off-by: RĂ©mi Rahir (rar) --- src/helpers/misc.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/helpers/misc.ts b/src/helpers/misc.ts index ceba5113f0..5d3f60a68b 100644 --- a/src/helpers/misc.ts +++ b/src/helpers/misc.ts @@ -131,13 +131,22 @@ export function getDefaultCellHeight(style: Style | undefined, numberOfLines?: n } export function computeTextWidth(context: CanvasRenderingContext2D, text: string, style: Style) { - context.save(); - context.font = computeTextFont(style); - const textWidth = context.measureText(text).width; - context.restore(); - return textWidth; + const font = computeTextFont(style); + if (!textWidthCache[font]) { + textWidthCache[font] = {}; + } + if (textWidthCache[font][text] === undefined) { + context.save(); + context.font = font; + const textWidth = context.measureText(text).width; + context.restore(); + textWidthCache[font][text] = textWidth; + } + return textWidthCache[font][text]; } +const textWidthCache: Record> = {}; + export function computeTextFont(style: Style): string { const italic = style.italic ? "italic " : ""; const weight = style.bold ? "bold" : DEFAULT_FONT_WEIGHT;