As you can see, something as simple as removing an invariant function call from a loop can provide a 20% increase. More importantly, failing to recognize and remove these invariants from loops can substantially slow down your applications (especially if you do it in many different places).
In this case, the invariant value was a call to the strlen() function. However, any nonscalar value used within a loop is a potential candidate for optimization. A very common example is looping based on the value of an array value such as the following (assume all variables are defined appropriately):
Although a function is not called, every access to the $myarray array requires a hash-table lookup internally within the engine. This is substantially slower than the access time required for scalar values:
The profiling results of these two methods provides the following information:
Method one took 3.676020026207 seconds. Method two took 2.6184829473495 seconds.
Method two was faster than Method one by 28.77%
As you can see, a near 30% performance increase is achieved by assigning an invariant array value to a scalar when in loops (even more dramatic than our original strlen() optimization).