Skip to content Skip to sidebar Skip to footer

Javascript For-loop Condition Caching

I've put together a jsperf test that compares for loops that iterate over an array with caching the array length condition vs not caching. I thought that caching the variable befor

Solution 1:

Can someone explain why this is?

This optimization and case is extremely common so modern JavaScript engines will automatically perform this optimization for you.

Some notes:

  • This is not the case when iterating a NodeList (such as the result of querySelectorAll
  • This is an overkill micro optimization for most code paths anyway, usually the body of the loop takes more time than this comparison anyway.

Solution 2:

The performance of the scenarios that you posted depends on how smart the JS engine's optimizer is. An engine with a very dump optimizer (or no optimizer at all) will likely be faster when you are using the variable, but you can't even rely on that. After all, length's type is well-known, while a variable can be anything and may require additional checks. Given a perfect optimizer, all three examples should have the same performance. And as your examples are pretty simple, modern engines should reach that point soon.

Post a Comment for "Javascript For-loop Condition Caching"