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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

AimbotMath
Trigonometry & Smoothing
MEMBER
Rep: 285
Join Date: Nov 2023
Posts: 27
Thanks: 73
6y ago · Jan 19, 2020 7:36 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?
AimbotMath · Angular Normalization & Smooth Angles
The following users thanked AimbotMath for this post:
DisasmGeek
Capstone & Keystone Specialist
MEMBER
Rep: 160
Join Date: Dec 2024
Posts: 21
Thanks: 38
6y ago · Jan 19, 2020 11:03 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.
DisasmGeek · Capstone / Keystone Engine Integration
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
6y ago · Jan 21, 2020 2:03 AM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...