"Unrolling" a loop by repeatedly "copy & pasting" the loop body can improve or reduce performance.
The outcome depends on...
- ...your JavaScript engine
- ...the code in the loop body
- ...how well documented your code is (no kidding!)
Let's analyze the performance using Google's popular V8 JavaScript engine (Chrome, Node):
Ordinary loop:
var count = 0;
for (var i = 0; i < 10; i++) {
count += 1;
}
Unrolled loop:
var count = 0;
count += 1;
count += 1;
...
count += 1;
Result: The unrolled loop is about 10x faster.
But what if we loop 1000 times instead of 10 times? Then the unrolled loop suddenly becomes more than 10x slower than the ordinary loop!
And what if we swap the simple arithmetic expression with a function call?
Ordinary loop:
function f() {
return 1;
}
var count = 0;
for (var i = 0; i < 10; i++) {
count += f();
}
Unrolled loop:
var count = 0;
count += f();
count += f();
...
count += f();
Result: The unrolled loop is about 50% faster.
But what if we add a comment to our function f?
function f() {
// bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
return 1;
}
Suddenly the unrolled loop is about 20% slower!
Why is that?
- V8 automatically inlines code when parsing functions whose body contains less than 600 characters, including whitespace and comments.
- V8 performs on-stack-replacement when a function is 'stuck' in a very long loop.
Regarding the last example: By adding a long > 600 character comment, we prevent V8 from inlining the function f during parsing and rely on the run-time optimization capabilities (such as 'on stack replacement') which target whole functions and loops but not manually repeated code.
As you can see, it is quite hard to predict the outcome of such micro-"optimization". So better don't do it - unless you target a specific version of a specific JS engine.
See https://jsfiddle.net/Lj9v7c2m/ for the performance analysis - you might get different results depending on your computer / browser / version.
document.write
and replace it with e. g. a placeholder to make this question more generic about 'loop unrolling' or similar? Otherwise most people will probably focus on thedocument.write
aspect / downvote. – Poi