Optimizing Loop Performance in JavaScript
- 1 minute read
JavaScript loops can be quite expensive, but they can also be optimzed.
My favorite trick is consolidating any expressions, statements, and/or assignments within the for
loop statement into variables.
Here’s an example of a loop that does not consolidate its sub-statement, array.length
into a variable:
const array = [1, 2, 3];
// Bad performance:
for (let i = 0; i < array.length; i++) {
// Do something
}
The body of a JavaScript loop and its for
loop statement are executed for every single iteration.
So in the above example, array.length
is repetitively calculated three times as much as it should be.
In the below example, this is solved by calculating array.length
and storing the value in a variable called len
before the loop, like this:
const array = [1, 2, 3];
const len = array.length;
// Better performance:
for (let i = 0; i < len; i++) {
// Do something
}
Conclusion
That’s all!
While unoptimized loops can have varying impacts on performance, it’s critical to remember that the entire for
statement and everything within gets executed at each iteration, regardless of complexity.