Unity 2022.3 LTS GC spikes every few seconds — string concat in Update
## The symptom
Unity 2022.3.21f1 with URP, a small 3D game heading toward a mobile build. In a development build, not the editor, the frame time graph was a clean sawtooth: 16ms for a few seconds, then a 180-220ms spike, then back to 16ms. Every three or four seconds like clockwork. That rhythm is almost always garbage collection. I turned on Deep Profile and sorted the hierarchy by the GC Alloc column:
string.Concat 1.6 MB / frame
String.Format 0.4 MB / frame
That was enough. One point six megabytes every frame at 60fps is about 100MB a minute of pure garbage, so the collector had every reason to run constantly.
## The code
void Update() {
hudText.text = "Score: " + score + " HP: " + hp +
" Time: " + Time.time.ToString("F2");
}
Every frame builds several temporary strings and boxes values along the way. The HUD only changes when the score or health changes, and the timer does not need to update sixty times a second, so nearly all of it was thrown away immediately.
## The fix
void Update() {
if (score != _lastScore || hp != _lastHp) {
_lastScore = score;
_lastHp = hp;
RebuildHud();
}
_timer += Time.deltaTime;
if (_timer >= 0.1f) {
_timer = 0f;
_timeText.text = Time.time.ToString("F2");
}
}
I also moved the string building into a StringBuilder field that gets Clear()ed rather than reallocated, and split the timer into its own Text element so it does not invalidate the whole HUD string ten times a second. With the TMPro version I am using, setting .text also rebuilds the mesh, so avoiding the redundant write mattered as much as the allocation.
## What went wrong along the way
I initially blamed Time.time.ToString("F2") and cached only that, which barely moved the needle. The spikes stayed because score and hp were still being concatenated every single frame with the rest of the line. I was looking at the most suspicious-looking call rather than the biggest allocation. That is on me. The Profiler had told me the answer; I just did not read the column properly. I also wasted time checking the GC settings in Project Settings, thinking I could tune my way out of it. You cannot tune your way out of a hundred megabytes a minute.
## Result
GC Alloc dropped to a few kilobytes per frame and the spikes disappeared entirely in the build. Frame time sits flat around 15-17ms. I fixed the same pattern in two other scripts after grepping the project for ToString inside Update; the build had been stuttering since we added the scoring system and nobody had thought to look at the HUD, because it looked so harmless. It is a boring fix, but if your Unity game stutters on a timer, sort by GC Alloc before you start rewriting your update loop.