Skip to content

Instantly share code, notes, and snippets.

@brainysmurf
Last active February 13, 2020 11:57
Show Gist options
  • Save brainysmurf/ada60079b88a33dc951bef9b35965fef to your computer and use it in GitHub Desktop.
Save brainysmurf/ada60079b88a33dc951bef9b35965fef to your computer and use it in GitHub Desktop.
Loop Benchmarks: V8 vs RHINO

Loop Benchmarks: V8 vs RHINO

Looping code was written to be compatible with both engines. It simply does nested loops with multiplication in the body.

  • Conclusion: V8 is way faster.
  • Caveat: This does not paint a complete picture.

Results:

RHINO

for loop took 1.616 seconds
for loop (optimised) took 1.678 seconds
.forEach loop took 1.451 seconds
.map loop took 3.345 seconds

V8

for loop took 0.004 seconds
for loop (optimised) took 0.002 seconds
.forEach loop took 0.017 seconds
.map loop took 0.031 seconds
var ITERSTEPS = 1000;
Logger.log("V8");
function runBenchmarks() {
var enter = function () {
this.array = [];
for (var k = 0; k < ITERSTEPS; k++) {
this.array.push(k);
}
this.start = new Date().getTime();
};
var exit = function (testName) {
this.end = new Date().getTime();
var duration = (this.end - this.start) / 1000;
Logger.log(testName + ' took ' + duration + ' seconds');
};
var forLoop = function () {
for (var i = 0; i < this.array.length; i++) {
for (var j = i; j > 0; j--) {
i * j;
}
}
};
var forLoopOptimized = function () {
var length = this.array.length; // optimized
for (var i = 0; i < length; i++) {
for (var j = i; j > 0; j--) {
i * j;
}
}
};
var forEachLoop = function () {
var length = this.array.length;
var arr = this.array;
arr.forEach(function (i) {
arr.slice(0, length - i).forEach(function (j) {
i * j;
});
});
};
var mapLoop = function () {
var arr = this.array;
var length = arr.length;
arr.map(function (i) {
arr.slice(0, length - 9).map(function (j) {
i * j;
});
});
}
var funcs = [ [forLoop, 'for loop'], [forLoopOptimized, 'for loop (optimised)'], [forEachLoop, '.forEach loop'], [mapLoop, '.map loop'] ];
funcs.forEach(function (values) {
var func = values[0];
var name = values[1];
enter.call(func);
func.call(func);
exit.call(func, name);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment