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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

DirectXRay
DirectX 12 / Vulkan Dev
MEMBER
Rep: 240
Join Date: Feb 2023
Posts: 31
Thanks: 60
6y ago · Jan 10, 2020 6:48 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?
DirectXRay · DirectX 12 & Vulkan Command Lists
The following users thanked DirectXRay for this post:
OffsetHunter
RTTI & NetVar Dumper
MEMBER
Rep: 175
Join Date: Jul 2024
Posts: 20
Thanks: 44
6y ago · Jan 10, 2020 10: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.
OffsetHunter · RTTI TypeDescriptors & NetVars
KeycardMaster
Item ESP & Unity UI Dev
MEMBER
Rep: 215
Join Date: Oct 2023
Posts: 19
Thanks: 54
6y ago · Jan 12, 2020 1:03 AM
#3
In Unity, you can also use StringBuilder with an integer-to-char conversion helper to avoid boxing.
KeycardMaster | Keycard & Objective ESP Specialist