If you find yourself in a typical loop situation, consider switching from using i < len
to i !== len
. This small change can greatly improve the speed of the loop execution, as checking for inequality is a quick operation. While caching the variable may not be essential, it certainly won't hurt.
To create a speedy loop in JavaScript, use the following structure:
for (var i = 0, len = myArray.length; i !== len; i++) {
}
UPDATE
In the past, I conducted some performance tests that led me to this conclusion. However, recent browser behavior has shifted, with the opposite now being true (<
is faster than !==
). To see for yourself, check out this test I just ran: http://jsperf.com/loop-inequality-check
It seems my earlier recommendation is no longer valid ;)