Does anyone know if this is still valid advice? I recall reading somewhere that the JIT has optimized around this problem.
Does anyone know if this is still valid advice? I recall reading somewhere that the JIT has optimized around this problem.
For general collections, things are more difficult, but I still expect java to optimize things in many cases. I haven't checked, though.
A C/C++ compiler has a tougher job. It can only move strlen calls out of a loop if it can determine that the strlen you call came from the correct <header> file and that there is no defined behavior under which either the pointer or its contents change inside the loop.
If it cannot do either, it must 'call' strlen each time through the loop (That 'call' can be inlined, especially if the compiler knows it is the standard library's strlen)
All the real optimization is done by the JIT which usually doesn't 'kick in' unless a segment of code gets called many times, in client mode I think the default in the hotspot vm is 1500, while in server mode is lower but I can't remember the default. I generally manually set it to something around 200 for sever apps.
As a result of this, the JIT may optimize this loop, it may not, it may optimize in the middle of a test, it all depends on how often the code its called. You can easily get different benchmark results by changing the -XX:CompileThreshold JVM parameter and will see variability in performance unless you 'warm up' the JIT forcing it to optimize.
See my other comment saying you should ignore any speed suggestions by the article.
for(int i=0, len=str.length(); i<len; i++)
One evaluation and you don't have an extra len variable hanging around.