Neil Fraser: News: JavaScript Loops

submited by
Style Pass
2022-01-27 17:00:17

As JavaScript interpreters get more sophisticated, their performance behaviours get more complex and more challenging to understand. Let's take the following code which counts to 100 million:

With this out of the way, here's a simple tool that wraps the user-provided code inside a function, runs it five times (to allow the function to 'warm up'), and prints the results to the browser console.

Now that we know the environment in which to run performant code, let's look at the best ways to loop in JavaScript. First let's try a simple "for" loop.

One optimization is to cache the length. This has a noticeable speed up in Chrome, at the expense of a small penalty in Firefox.

ES6 adds the "for-of" loop. It's just a performance disaster in every browser. Avoid this construct for performant code.

The performance of unrolled loops is wild. Horrible initial penalty when cold, then dramatic warmup after one or two executions.

Leave a Comment
Related Posts