[SOLVED] Phaser 3 vs Phaser 2 Text Creation Performance

I can’t guarantee that this is the exact reason, but it’s a common offender when making many text objects at once. To render text, Phaser has to measure the font. Because browsers don’t provide an API to do it efficiently, this is done by creating a separate canvas and counting pixels, which is a really slow operation.

I haven’t worked with Phaser 2 for a long time, but looking at the source code, it seems that it automatically caches the metrics for each font. Phaser 3 doesn’t do that automatically, so it measures the font each time you create an object. You should create one text object with the desired font, then store its metrics somewhere using text.getTextMetrics(). You can then pass this object into the text style of new Text objects to avoid measuring the font:

const metrics = text.getTextMetrics();

// ...

this.add.text(0, 0, 'some text', {
    fontFamily: 'Arial',
    fontSize: 24,
    metrics: metrics
});

Note that changing the font in any way after the text is created will make Phaser recalculate the metrics. You should also make sure that the metrics you pass come from a text object with the exact same font.

5 Likes