Introduction
I like looking at the code behind of websites I admire. In doing so I think I've seen one of the most common mistakes when it comes to
JavaScript performance. This is not something that would popup quickly because the effect is minimal. But I like coding, so I also like doing right.
Background
The type of loop that I often see coded wrong and which I also used to code wrong in the past is the
for
loop. And I believe the reason for doing it wrong is, not fully
understanding what the syntax does.
This is the example from http://www.w3schools.com/js/js_loop_for.asp:
for (statement 1; statement 2; statement 3)
{
}
This goes on stating;
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
Although this is essentially right, they forget to say that Statement 2 will be executed every time the loop ends a code block.
The wrong example
for(var i=0; i < myarray.length; i++) {
}
Why is this wrong?
myarray.length
will be executed after every code block. Now if this array is small, the
JavaScript engine will answer this question quickly.
But what if the condition would be some function that could take a while?
The right example
for(var i=0, j=myarray.length; i < j; i++) {
}
Now the length of myarray
will only be executed at the start of the loop.
Conclusion
This might seem like a very little win if it comes to performance. But I believe people should always do things right. If myarray.length
would be something
like calculateSomeVariableLengthByRunningLengthyFunction()
, this could end up as a performance penalty.
And even the w3schools tutorial doesn't explain this the right way.