Skip to content

Commit 3b3c40a

Browse files
committed
perf: cache TextLayoutResult in DisplayListRenderer to avoid per-frame text measurement
1 parent 0d2c68e commit 3b3c40a

1 file changed

Lines changed: 19 additions & 6 deletions

File tree

  • multiplatform-markdown-renderer-latex/src/commonMain/kotlin/com/mikepenz/markdown/latex/renderer

multiplatform-markdown-renderer-latex/src/commonMain/kotlin/com/mikepenz/markdown/latex/renderer/DisplayListRenderer.kt

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import androidx.compose.ui.graphics.drawscope.DrawScope
88
import androidx.compose.ui.graphics.drawscope.Fill
99
import androidx.compose.ui.graphics.drawscope.Stroke
1010
import androidx.compose.ui.graphics.takeOrElse
11+
import androidx.compose.ui.text.TextLayoutResult
1112
import androidx.compose.ui.text.TextMeasurer
1213
import androidx.compose.ui.text.TextStyle
1314
import androidx.compose.ui.text.drawText
@@ -29,6 +30,8 @@ internal class DisplayListRenderer(
2930
private val fontMap: Map<String, FontFamily>,
3031
private val colorOverride: Color = Color.Unspecified,
3132
) {
33+
private val glyphCache = HashMap<GlyphCacheKey, TextLayoutResult>()
34+
3235
fun draw(drawScope: DrawScope) {
3336
for (item in displayList.items) {
3437
when (item) {
@@ -55,12 +58,15 @@ internal class DisplayListRenderer(
5558
val targetPx = fontSizePx * glyph.scale
5659
val fontSizeSp = (targetPx / (density * fontScale)).toFloat()
5760

58-
val style = TextStyle(
59-
fontFamily = fontFamily,
60-
fontSize = fontSizeSp.sp,
61-
color = color,
62-
)
63-
val result = textMeasurer.measure(str, style)
61+
val key = GlyphCacheKey(fontFamily, charCode, fontSizeSp, color)
62+
val result = glyphCache.getOrPut(key) {
63+
val style = TextStyle(
64+
fontFamily = fontFamily,
65+
fontSize = fontSizeSp.sp,
66+
color = color,
67+
)
68+
textMeasurer.measure(str, style)
69+
}
6470
drawText(
6571
textLayoutResult = result,
6672
topLeft = Offset(
@@ -118,6 +124,13 @@ internal class DisplayListRenderer(
118124
}
119125
}
120126

127+
private data class GlyphCacheKey(
128+
val fontFamily: FontFamily,
129+
val charCode: Int,
130+
val fontSizeSp: Float,
131+
val color: Color,
132+
)
133+
121134
/** Convert a Unicode code point to a String (supports supplementary planes). */
122135
private fun Int.toCodePointString(): String {
123136
return if (this < 0x10000) {

0 commit comments

Comments
 (0)