Benchmark - while vs. for
by basickarl
HTML
<script src="https://cdn.jsdelivr.net/firebuglite/1.4.0/firebug-lite-debug.js"></script>
<script src="https://cdn.jsdelivr.net/g/lodash@4.13.1,platform.js@1.3.1,benchmarkjs@2.1.1"></script>
JavaScript
'use strict';
(function() {
// add your functions here
var i,
len = 100000,
lenRev = 99999;
// add the actual tests here, suite index, name, function
function yourTests() {
addTest(0, 'while i+=1', function() {
i = 0;
while (i < len) {
1 + 1;
i += 1;
}
});
addTest(0, 'while i-=1', function() {
i = lenRev;
while (-1 < i) {
1 + 1;
i -= 1;
}
});
addTest(0, 'for i+=1', function() {
for (i = 0; i < len; i += 1) {
1 + 1;
}
});
addTest(0, 'for i-=1', function() {
for (i = lenRev; - 1 < i; i -= 1) {
1 + 1;
}
});
}
// put functions to test in here
var suitesData = [];
function addTest(index, name, func) {
if (!suitesData[index])
suitesData[index] = [];
suitesData[index].push({
name: name,
func: func
});
}
yourTests();
console.log(platform.name); // Chrome
console.log(platform.version); // 51.0.2704.106
console.log(platform.layout); // Blink
console.log(platform.os); // Linux 64-bit {architecture=64, family="Linux", ...}
console.log(platform.description); // Chrome 51.0.2704.106 on Linux 64-bit
console.log(platform.manufacturer); // Apple
console.log(platform.product); // iPad
// variables
var suite,
suites = [],
i = 0,
bj,
bk;
for (bj = 0; bj < suitesData.length; bj += 1) {
// new benchmark object
suite = new Benchmark.Suite();
// add tests
for (bk = 0; bk < suitesData[bj].length; bk += 1) {
suite.add(suitesData[bj][bk].name, suitesData[bj][bk].func);
}
suite
// invoke before running
.on('start', function() {
console.log('Running tests, please wait...');
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
...