I have some levels, with enemy waves and two Text components for:

Enemies killed, like: "13/57" Waves passed, like: "68"

On each enemy kill/new wave, I make a ToString() call, in order to update these UI components. I already separated "13", "/" and "57" into different Text's to prevent concatenation.

In early game, there's no overhead, but if the game gets more dynamic in time and there are 30-40 enemies on the screen, GC get's mad really quickly. It's not a constant Update(){ tostring() } call, but it's noticable, really, especially while rendering.

The game itself is really, really expensive, so I need to optimize what I can.

The point

The maximum amount of enemies is 200, so this is the maximum string that will be made through ToString().

There's no maximum wave, but it's quite hard to get to 500 (late-game).

I made a simple system:

private static readonly string[] STRING_NUMBERS;

static MathUtils(){
    STRING_NUMBERS = new string[1000];
    for(int i=0;i<STRING_NUMBERS.Length;i++)
        STRING_NUMBERS[i] = i.ToString();

public static string GetStringNumber(int i)
    if(i > STRING_NUMBERS.Length - 1)
        return i.ToString();

    return STRING_NUMBERS[i];

As you can see, I preallocated 1000 strings: "0", "1" ... "999".

If I try to get a higher number, it would ToString() anyways.

My question is, would it work? is this worth? Did I forget something?

  • \$\begingroup\$ Are you sure that the method to get and print a wave and enemies killed are the bottleneck here? Sounds like a simple task for a gc or processor. The performance issues might be more related to the number of enemies on screen? \$\endgroup\$ – John Feb 28 '18 at 10:13
  • \$\begingroup\$ Maybe you do not have to update the number of kills and waves for each tick/cycle, instead only update when an "enemy killed"-event or "new wave"-event is fired. And instead of using ToString() all the time, you could call it once for each event, and then save the text in a variable, reusing it for drawing. \$\endgroup\$ – John Feb 28 '18 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.