Benchmark - new Array() vs. []
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 arr,
x = 1000;
// add the actual tests here, suite index, name, function
function yourTests() {
addTest(0, 'new Array()', function() {
arr = new Array();
});
addTest(0, '[]', function() {
arr = [];
});
addTest(1, 'Array(x)', function() {
arr = new Array(x);
});
addTest(1, '[] & arr[x-1] = undefined', function() {
arr = [];
arr[x - 1] = undefined;
});
}
// 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'));
// runs the next suite in the suites array if it exists
if (suites[i++]) {
suites[i].run({
'async': true
});
}
});
...