Skip to content

Commit

Permalink
[FIX] rendering: cache text width
Browse files Browse the repository at this point in the history
Computing the text width is expensive, so we cache it

Task 3354651

closes #2558

Signed-off-by: Rémi Rahir (rar) <[email protected]>
  • Loading branch information
LucasLefevre committed Jun 20, 2023
1 parent 1b5ce1c commit 1ad0040
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/helpers/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Record<string, number>> = {};

export function computeTextFont(style: Style): string {
const italic = style.italic ? "italic " : "";
const weight = style.bold ? "bold" : DEFAULT_FONT_WEIGHT;
Expand Down

0 comments on commit 1ad0040

Please sign in to comment.