Flutter TextPainter slowness

My app is spending 16%-35% of it’s time rendering text on a canvas, so basically calling:

textPainter
        ..text = TextSpan(...)
        ..layout()
        ..paint(canvas, position);

[Adding width constraints to the layout call doesn’t change anything performance-wise].

I am not doing anything fancy – each text to render is one line, has no effects (rotation, halo, etc), is using the default font at normal weight, etc. Just simple strings to render.

I am rendering roughly 500 small pieces of text (4-5 digit depths on charts).

Is there some magic flag I can turn on to speed this up (some caching flag for layouts or painting?).

Or any other technique I can use?

Text rendering is now the performance bottleneck in my app, which surprises me since in the JavaFX version of the app text rendering is very quick and isn’t a performance issue.

thanks
CW

1 Like

I recommend avoiding calling layout() on every frame and instead caching your text layouts so they’re created only once per unique text and style. The expensive part of text rendering is layout (shaping and measuring), while painting is relatively cheap, so reusing a pre-laid-out TextPainter or Paragraph can significantly reduce overhead. If your labels repeat often, you can go even further and render each unique string once into a Picture or Image and just draw that each frame. If the text is static, move it into a separate CustomPainter wrapped in a RepaintBoundary so it doesn’t repaint unnecessarily. If the text truly changes every frame, consider using ui.ParagraphBuilder directly. And always measure performance in profile or release mode, not debug, to get realistic results.

1 Like

To clarify, you are suggesting I cache a TextPainter object (one that has had its TextSpan set and layout done) per unique text and style?

thanks
CW