I’m writing a casino game in which I need to encrypt all the data I pass through sockets, so I want as much performance as I can get, because encryption and decryption may happen quite a lot, and I don’t want it to be laggy.
My question is which is faster performance-wise when you have a String and you want to get it’s characters at high speed, myString.charAt(i) or having var a:Array = myString.split(''); and then getting them like this a[i];
My for cycle may run 60-100 times or more. Thanks in advance
benbjo’s advice is a solid one. If performance is really a concern, the best test case is the situation where you’re actually going to use your code, not least because of garbage collection and the JIT’er making things unpredictable in terms of the actual performance.
That said, the
charAtapproach in general will be (20-50%) faster thansplit(). Memory-wise there shouldn’t be much of a difference – both approaches are creating a new string per character. In addition to that, thesplit()obviously also creates an additional array.A comparison of these two methods:
charAt:
split:
The relevant compiled ABC byte code is predictably identical between the two, except the call to split, and the array access vs. calling
charAt(). In other words, no crazy optimization stunts by the ASC compiler (those are rare anyway).10 runs, 1000 iterations each of the above code, release build on release player:
Avg = average time for each run (of 1000 iterations)
Min = minimum time for a single run
Max = maximum time for a single run
Iter = average time for a single iteration.
The variance between runs is fairly large, likely due to garbage collection happening during some of the runs. But the result is consistently in favour of
charAt(). Making thesplit()call once before each run rather than redoing it in each iteration doesn’t make much difference. In other words, the difference in performance really does lie in accessing the array being slower than callingcharAt(). It’s not the huge difference, however, that you’ll get from, say, usingindexOfinstead of a regex for searching a string.In general, although it’s not a hard-and-fast rule, the most obvious approach to simple tasks like string manipulation will likely be the faster one. The FlashPlayer team spent a lot of time optimizing string manipulation, concatenation etc.