feat(G2DDrawFont): implement caching for TextLayout to improve performance

chore(pom.xml): bump version to 1.0.21 and add Caffeine cache dependency
This commit is contained in:
extio-de
2026-06-17 14:33:10 +02:00
parent a758d264f5
commit ea3ed7e31d
2 changed files with 23 additions and 3 deletions

View File

@@ -8,10 +8,15 @@ import java.awt.Shape;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.text.AttributedString;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import de.extio.game_engine.renderer.model.RenderingBo;
import de.extio.game_engine.renderer.model.RenderingBoLayer;
import de.extio.game_engine.renderer.model.bo.DrawFontRenderingBo;
@@ -37,6 +42,11 @@ public class G2DDrawFont extends G2DAbstractRenderingBo implements DrawFontRende
private static final AtomicReference<Font> cachedFallbackFontRef = new AtomicReference<>();
private static Font baseFont;
private static final Cache<TextLayoutParameters, TextLayout> textLayoutCache = Caffeine.newBuilder()
.maximumSize(250)
.expireAfterAccess(Duration.ofMinutes(1))
.build();
static {
final Map<TextAttribute, Object> attributes = new HashMap<>();
@@ -250,8 +260,11 @@ public class G2DDrawFont extends G2DAbstractRenderingBo implements DrawFontRende
}
private static TextLayout createTextLayout(final String text, final Graphics graphics, final int size_, final double scaleFactor) {
final var attributedString = createAttributedString(text, size_, scaleFactor);
return new TextLayout(attributedString.getIterator(), ((Graphics2D) graphics).getFontRenderContext());
final var cacheKey = new TextLayoutParameters(text, size_, scaleFactor);
return textLayoutCache.get(cacheKey, key -> {
final var attributedString = createAttributedString(key.text, key.size_, key.scaleFactor);
return new TextLayout(attributedString.getIterator(), ((Graphics2D) graphics).getFontRenderContext());
});
}
private static AttributedString createAttributedString(final String text, final int size_, final double scaleFactor) {
@@ -276,5 +289,8 @@ public class G2DDrawFont extends G2DAbstractRenderingBo implements DrawFontRende
}
return attributedString;
}
private record TextLayoutParameters(String text, int size_, double scaleFactor) {
}
}