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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

KronoDev
C++ / Game Modder
MEMBER
Rep: 195
Join Date: Jan 2023
Posts: 32
Thanks: 48
3y ago · Apr 19, 2023 5:03 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?
KronoDev - Keep coding, keep learning
The following users thanked KronoDev for this post:
DarkLogic
Game Logic & SDK Developer
MEMBER
Rep: 180
Join Date: Jun 2024
Posts: 28
Thanks: 41
3y ago · Apr 19, 2023 6:08 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.
DarkLogic | Virtual method tables & SDKs
SigScannerPro
Pattern Scanning & IDA
MEMBER
Rep: 210
Join Date: Jul 2023
Posts: 25
Thanks: 52
3y ago · Apr 20, 2023 7:08 PM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
SigScannerPro · Pattern scanning & Byte masking