Optimizing timer for mobile

I am currently running a timer in my game which runs exactly as intended like this…

public class TimerController : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI timeText;

private float startTime;
private float elapsedTime;
TimeSpan timePlaying;

private void Start()
{
startTime = Time.time;
}

private void Update()
{
elapsedTime = Time.time - startTime;
timePlaying = TimeSpan.FromSeconds(elapsedTime);
timeText.text = timePlaying.ToString(“mm’ : ‘ss’ . 'ff”);
}
}

However after learning more about optimization (especially for mobile where I plan to release my game) I realize that creating and updating a string in the update function every frame for the timer is costly. I thought about using a coroutine instead in the start function to start a timer that waits one second to save on performance however I want to keep the format of milliseconds as the game is heavily based on highscores with the timer. Can anyone provide any insight as to how to approach this problem in a way that can maybe avoid the update function or improve performance in general?

Have you proven in your case this is actually a problem for your game?

Or is this just speculative optimization?

DO NOT OPTIMIZE CODE RANDOMLY… always start by using the profiler:

Window → Analysis → Profiler

https://discussions.unity.com/t/841163/2

Optimizing UnityEngine.UI setups:

https://discussions.unity.com/t/846847/2

One thing people do with clocks is break them apart into minutes, colon, second each with their own Text component. This avoids the ToString cost because you can lookup a precached string representation of that integer and set it to the text component.

Since you want milliseconds, you’d need another colon and milliseconds too, and you can’t avoid updating it every frame to millisecond resolution. That makes the situation more difficult and the optimization less worthwhile because you’d need to cache 0…999 strings for integers. On one hand, you save a small amount of garbage per frame, but on the other hand you have a 1,000 strings cached - granted, small strings, but it’s clutter.

Is it worth it? Some people have a “zero per frame garbage” rule. This optimization would help you achieve that. But it’s certainly not a priority now, and as Kurt pointed out you don’t know if it’s really worth your time relative to other optimizations you could do.

For example, perhaps the timed activity lasts too short of a time to matter, and you could manually run the Garbage Collector between scenes when nobody would notice anyway. People want to minimize GC to prevent frame hitches since it’s an expensive operation, but perhaps in the context of the game, relative to other performance bottlenecks, there could be better places to put your time. That’s what the Profiler is for.

1 Like