Re: Javascript array size and performance
Reply #1 –
Firstly, I want to say that when it comes to optimization, never ever assume something is faster "because it should be." Besides the issue of testing your assumptions, there's also the problem of readability/understandability vs speed, and if you're going to be sacrificing one, you'd better be making up for it with the other enough to warrant the change, and you better know how much you're gaining in one area over the other.
Case in point, the ++i vs i++ debacle in C++. When i is an integer, it's argued that ++i should be faster since it increments i, and then returns it (2 ops), instead of i++ which stores the value of it, increments i, and then returns the stored value (3 ops). Since the 486 era of cpus, these two should actually go the same speed since each core of a cpu can do a limited number of operations in parallel (if the operations are independent of each other), so both end up returning after 2 ops. Moreover, in the case of loops, i++ should actually be faster since it can do the loop check while it's storing i, so if the value of i is not immediately used in the loop, it can start the loop after 1 op whereas ++i has to increment the i and then do the check. But, really this is all a mute point because compilers will optimize out stuff like this anyway, so why the hell bother in the first place? If your code needs to know the difference between i++ vs ++i, then you're making your code more complicated and harder to understand for an optimization that doesn't even exist anymore. The only case where ++i vs i++ makes a difference is when i is a complicated class and you're overloading ++ (though I'd worry about this as well since it's also potentially making the code less readable).
So the moral of that story? Don't listen to other people, and test your optimization assumptions to make sure there is a speed gain and that it's worth the reduction in readability. Don't even listen to my argument above, test the difference between ++i and i++ yourself in your compiler, language etc.
Ok, with that out of the way, I would always use the standard for loop to add stuff to an array. For the reverse fill example you gave, my guess is that JavascriptCore doesn't realize that your array is going to be a fixed-size array and should be implemented as a list type instead of a hashmap. Once you do it in the forward direction the compiler figures out it should be working on a vector and does it that way. Then with the fixed size array, it knows from the start how big to make the list ahead of time.