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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

GameDevSam
Indie Game Developer
VIP
Rep: 90
Join Date: Jul 2020
Posts: 8
Thanks: 22
6y ago · Jul 19, 2020 3:30 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?
GameDevSam · Indie Game Developer
Solo indie dev building games with Unity, Monogame, and cust...
The following users thanked GameDevSam for this post:
BinaryParser
File Format Reverser
MEMBER
Rep: 128
Join Date: Nov 2024
Posts: 6
Thanks: 78
6y ago · Jul 19, 2020 6:50 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.
BinaryParser · File Format Reverser
Parsing custom binary asset formats, mesh chunks, and compre...
LambdaMaster
Functional C#
MEMBER
Rep: 56
Join Date: Jun 2025
Posts: 7
Thanks: 85
6y ago · Jul 19, 2020 10:50 PM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
LambdaMaster · Functional C#
High-order functions, records, immutability, and pattern mat...