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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

VectorByte
Graphics & DirectX Dev
VIP
Rep: 420
Join Date: Aug 2022
Posts: 39
Thanks: 115
3y ago · Apr 1, 2023 10:39 AM
#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?
VectorByte | DirectX 11/12 Hooking & ImGui Overlays
Quote
Math is the language of game engines.
The following users thanked VectorByte for this post:
ShadowPwn
Security Researcher
MEMBER
Rep: 150
Join Date: Feb 2024
Posts: 19
Thanks: 35
3y ago · Apr 1, 2023 2:21 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.
ShadowPwn · Security & Anticheat Analysis
VMT_Hooker
VMT / Detours Engineer
VIP
Rep: 310
Join Date: Mar 2023
Posts: 22
Thanks: 80
3y ago · Apr 1, 2023 3:21 PM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
VMT_Hooker - Virtual method table swapping made easy