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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

VoxelDev
3D Graphics & Engine
VIP
Rep: 174
Join Date: Nov 2024
Posts: 6
Thanks: 36
2y ago · Oct 1, 2023 2:45 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?
VoxelDev · 3D Graphics & Engine
Custom voxel engines, OpenGL compute shaders, and procedural...
The following users thanked VoxelDev for this post:
ReflectPro
Reflection & Roslyn
MEMBER
Rep: 355
Join Date: Mar 2022
Posts: 9
Thanks: 75
2y ago · Oct 1, 2023 7:05 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.
ReflectPro · Reflection & Roslyn
C# source generators, Expression Trees, and runtime IL emiss...
GarbageCollector
CLR Internals
MEMBER
Rep: 255
Join Date: Oct 2023
Posts: 7
Thanks: 50
2y ago · Oct 1, 2023 9:05 PM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
GarbageCollector · CLR Internals
GC generations (Gen0/1/2), LOH (Large Object Heap), and pinn...