Sphere
Log in Join
☆ 8

unity gc allocation spikes every few seconds in mobile build

Unity 2021.3.29f1, building for Android. Profiler shows a 4ms GC spike about every 3 seconds. Deep Profile points at a script that does string concatenation in Update to build an FPS counter: text = "FPS: " + (1/Time.deltaTime).ToString("F0") + " ms: " + Time.deltaTime.ToString("F2"); That runs every frame and allocates strings, so garbage collects. I know I should use StringBuilder but it still allocates the final string. What's the standard fix here - update the text every 0.5s and reuse a StringBuilder? Also the FPS math itself is wrong, 1/deltaTime gives an instantaneous value that jumps around, but that's a separate issue.

⚑ Report

4 replies

☆ 0
R regex ·2026-11-04#1

StringBuilder avoids the intermediate allocations but ToString still allocates one string, which is fine at 2x/sec. The bigger fix is not touching the Text component every frame - the setter marks the canvas dirty. Cache a counter, accumulate frames and time, and only update every 0.5s. For FPS show a smoothed average: frames/time over the interval, not 1/deltaTime. Also use InvariantCulture to avoid a culture allocation.

⚑ Report
☆ 0
C cactus11 ·2026-11-05#2

Switched to accumulate frames and divide by elapsed time, update text twice a second. Spikes dropped from 4ms to basically nothing. I used a StringBuilder and SetText once per interval. Interesting that the canvas dirty flag was as bad as the strings - I hadn't thought about that at all.

⚑ Report
☆ 0
C cron48 ·2026-11-10#3

The canvas rebuild is often the hidden cost. If you use TextMeshPro instead of uGUI Text, SetText with a preallocated StringBuilder has a dirty-but-no-realloc path. Worth it if you have a lot of HUD text. Also check your Update for any LINQ or foreach over arrays that box - those add steady allocations that make GCs more frequent even if each one is small.

⚑ Report
☆ 0
M moth ·2026-11-12#4

Went down the rabbit hole and found two more allocators in the same script: a Physics.Raycast with an out RaycastHit and a lambda in a Button.onClick.AddListener created every frame. Moved the listener to Start and cached the hit. Now GC happens maybe once a minute and the spike is under 1ms. Moral: deep profile the whole script, not just the line that looks guilty.

⚑ Report
Log in to reply.