3

I'd like to display a millisecond timer value in a game.

String.format is hellishly slow on Android, so I can't use it. I currently use this:

long elapsedMillis = ...; //elapsed milliseconds
int whole = (int)(elapsedMillis / 1000);
int fraction = (int)(elapsedMillis % 1000);
StringBuilder sb = new StringBuilder("TIME:");
sb.append(whole);
sb.append('.');
if(fraction < 10)
sb.append("00");
else if(fraction < 100)
sb.append("0");
sb.append(fraction);
g.drawText(sb.toString(), ...);

but I think it could be done faster. Can you please guide me in the right direction? Thanks


related question

Community
  • 1
  • 1
Axarydax
  • 16,353
  • 21
  • 92
  • 151
  • 1
    `final` variables perhaps. Else I couldn't image more than what you have now. Is this mission critical code & did you consider to put it in a NDK function? – Sebastian Roth Dec 16 '10 at 08:25
  • used static StringBuilder and final variables, and TIME: pre-drawn. – Axarydax Dec 16 '10 at 09:41

1 Answers1

3

some ideas:

  • use a static StringBuilder initialized with a large capacity
  • use a native function
  • have "TIME:" pre-drawn (I assume it does not move)
  • keep the time value in milliseconds
Stéphane
  • 6,920
  • 2
  • 43
  • 53