Skip to content

Instantly share code, notes, and snippets.

@Spyryto
Created October 7, 2016 10:36
Show Gist options
  • Save Spyryto/67b13d4e78cdd0d7a7346410d5becf12 to your computer and use it in GitHub Desktop.
Save Spyryto/67b13d4e78cdd0d7a7346410d5becf12 to your computer and use it in GitHub Desktop.
For loop benchmark (http://jsbench.github.io/#67b13d4e78cdd0d7a7346410d5becf12) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>For loop benchmark</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
Benchmark.prototype.setup = function () {
var array = [];
for (var i = 1000; i-- ;) array.push(i);
var sum = 0
function add( n ) {
sum += n;
}
function addFrom( array, i ) {
sum += array[i];
}
};
suite.add("Loop, function call", function () {
// Loop, function call
for ( var i = 1; i <= array.length; i++ ) {
add( array[i] );
}
});
suite.add("Loop, function call #2", function () {
// Loop, function call #2
for ( var i = 1; i <= array.length; i++ ) {
addFrom( array, i );
}
});
suite.add("Loop, inlined code", function () {
// Loop, inlined code
for ( var i = 1; i <= array.length; i++ ) {
sum += array[i];
}
});
suite.add("Loop, cached value, function call", function () {
// Loop, cached value, function call
for ( var i = 1, l = array.length; i <= l; i++ ) {
add( array[i] );
}
});
suite.add("Loop, cached value, inlined code", function () {
// Loop, cached value, inlined code
for ( var i = 1, l = array.length; i <= l; i++ ) {
sum += array[i];
}
});
suite.add("Reverse loop, implicit comparison, function call", function () {
// Reverse loop, implicit comparison, function call
for ( var i = array.length; i--; ) {
add( array[i] );
}
});
suite.add("Reverse loop, implicit comparison, inlined code", function () {
// Reverse loop, implicit comparison, inlined code
for ( var i = array.length; i--; ) {
sum += array[i];
}
});
suite.add("Reverse loop, implicit comparison, function call #2", function () {
// Reverse loop, implicit comparison, function call #2
for ( var i = array.length; i--; ) {
addFrom( array, i );
}
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("For loop benchmark");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment