Ignoring all code cleanliness and readability, which script will finish quicker?
This:
for(var i = 0; i < 10; i++){
--do that thing--
}
Or this:
--do that thing--
--do that thing--
--do that thing--
--do that thing--
--do that thing--
--do that thing--
--do that thing--
--do that thing--
--do that thing--
--do that thing--
Or are they the same, performance-wise?
"Unrolling" a loop by repeatedly "copy & pasting" the loop body can improve or reduce performance.
The outcome depends on...
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With