I wonder what the performance difference is in terms of referencing a local var vs. referencing an object property? Surely it's negligible?
I wonder what the performance difference is in terms of referencing a local var vs. referencing an object property? Surely it's negligible?
Question: how can the compiler be sure an array's length wouldn't have changed? I suppose it could examine the code within the loop, but then the same could be said for strlen. What's the difference?
This is a specific example of dataflow analysis, which is a fascinating area of compiler design. Usually you'll use something like a use-def chain to figure out all the points where a variable might've been defined. If all of those are outside of the loop, then the computation itself may be moved outside of the loop too, and the loop just refers to the temporary that's the result. I'd encourage you to pick up a book on compiler design if you're interested; here's the Wikipedia article:
http://en.wikipedia.org/wiki/Use-define_chain
This explicitly doesn't apply to "smart" containers like Vectors, which automatically resize themselves. If you were to inline these methods, you'd see that the internal buffer pointer may change inside the loop (assuming that you call functions that mutate the object; if you don't, and the language has a notion of const-correctness, a sufficiently smart compiler could probably optimize them too), and so the compiler can't move any code outside. Same with strlen; its return value depends upon the contents of the memory buffer pointed to, so unless the compiler can prove that that memory buffer never changes (hard; any function may reach in through a pointer and set a character to null), it can't optimize the call away.
Thanks again, its great to learn something new.
http://www.amazon.com/Compilers-Principles-Techniques-Alfred...
I'm also partial to Appel's "Modern Compiler Implementation in ML", because it goes into more detail about techniques for compiling functional languages:
http://www.amazon.com/Modern-Compiler-Implementation-Andrew-...
In other words, it's not very helpful to say "this is so slow, you should do this instead" without at least trying to quantify the difference somehow.
With 10M entries in the array, the "slow" way takes 509 ms and the "faster" way takes 362 ms. So we can save roughly 15 nanoseconds per iteration. Or a 30% speedup - assuming nothing happens inside the loop.
(Of course the numbers may vary wildly per browser.)
Somehow I doubt this is the performance problem behind slow web pages.