Skip to content

Commit 0969ddd

Browse files
committed
[IMP] perfs: speed up computeTextWidth
The function `computeTextWidth` uses a cache to store the width of a text, but we would make canvas operations `ctx.save()/restore()` even if the width is already in the cache. For an animation on 350 cells, we went from spending 25ms in `computeTextWidth` to 4ms. Task: 4805149
1 parent 0f635b2 commit 0969ddd

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

src/helpers/text_helper.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -59,20 +59,22 @@ export function computeTextWidth(
5959
fontUnit: "px" | "pt" = "pt"
6060
) {
6161
const font = computeTextFont(style, fontUnit);
62-
context.save();
63-
context.font = font;
64-
const width = computeCachedTextWidth(context, text);
65-
context.restore();
66-
return width;
62+
return computeCachedTextWidth(context, text, font);
6763
}
6864

69-
export function computeCachedTextWidth(context: CanvasRenderingContext2D, text: string) {
70-
const font = context.font;
65+
export function computeCachedTextWidth(
66+
context: CanvasRenderingContext2D,
67+
text: string,
68+
font: string
69+
) {
7170
if (!textWidthCache[font]) {
7271
textWidthCache[font] = {};
7372
}
7473
if (textWidthCache[font][text] === undefined) {
74+
const oldFont = context.font;
75+
context.font = font;
7576
textWidthCache[font][text] = context.measureText(text).width;
77+
context.font = oldFont;
7678
}
7779
return textWidthCache[font][text];
7880
}
@@ -280,19 +282,19 @@ export function clipTextWithEllipsis(
280282
text: string,
281283
maxWidth: number
282284
) {
283-
let width = computeCachedTextWidth(ctx, text);
285+
let width = computeCachedTextWidth(ctx, text, ctx.font);
284286
if (width <= maxWidth) {
285287
return text;
286288
}
287289
const ellipsis = "…";
288-
const ellipsisWidth = computeCachedTextWidth(ctx, ellipsis);
290+
const ellipsisWidth = computeCachedTextWidth(ctx, ellipsis, ctx.font);
289291
if (width <= ellipsisWidth) {
290292
return text;
291293
}
292294
let len = text.length;
293295
while (width >= maxWidth - ellipsisWidth && len-- > 0) {
294296
text = text.substring(0, len);
295-
width = computeCachedTextWidth(ctx, text);
297+
width = computeCachedTextWidth(ctx, text, ctx.font);
296298
}
297299
return text + ellipsis;
298300
}

0 commit comments

Comments
 (0)