Home / Forums / How to avoid GC spikes with string formatting in Unity / .NET hot paths? [Discussion #7]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How to avoid GC spikes with string formatting in Unity / .NET hot paths? [Discussion #7]

BlazorKing
Full-Stack C#
MEMBER
Rep: 199
Join Date: Oct 2023
Posts: 6
Thanks: 26
2y ago · Oct 10, 2023 8:21 PM
#1
My game loop is getting occasional micro-stutters because string interpolations $"Score: {score}" are generating garbage memory every frame. How can I format text with zero heap allocations?
BlazorKing · Full-Stack C#
Building real-time web applications and desktop tools with B...
The following users thanked BlazorKing for this post:
UI_Wizard
ImGui Widget Dev
MEMBER
Rep: 72
Join Date: Feb 2021
Posts: 6
Thanks: 95
2y ago · Oct 10, 2023 9:32 PM
#2
Use ZString or string.Create with a stackalloc Span<char>! In .NET 6+, ISpanFormattable allows writing numbers directly into a char buffer: score.TryFormat(span, out int written). Then pass the buffer directly to your renderer without creating an intermediate string.
UI_Wizard · ImGui Widget Dev
Writing complex custom ImGui widgets: color pickers, curve e...
MemoryLeaker
C++ Enthusiast
VIP
Rep: 182
Join Date: Sep 2022
Posts: 6
Thanks: 20
2y ago · Oct 11, 2023 3:32 AM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
MemoryLeaker · C++ Enthusiast
Always remembering to delete my heap pointers... most of the...