Skip to content

Instantly share code, notes, and snippets.

@maxvipon
Created September 13, 2016 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxvipon/336d5ab739711c95bc3ed19e4b8410b8 to your computer and use it in GitHub Desktop.
Save maxvipon/336d5ab739711c95bc3ed19e4b8410b8 to your computer and use it in GitHub Desktop.
Bench const array vs dynamic array
const Benchmark = require('benchmark').Benchmark;
const suite = new Benchmark.Suite();
function uid() {
return 'xxx'.replace(/x/g, function(c) {
return Math.floor(Math.random()*10);
});
}
const count = 100;
var numbers = new Array(count);
for (var i = 0; i < count; i++) {
numbers[i] = uid();
}
suite
.add('const', function() {
var a;
if (Math.random() > 0.5) {
a = [Number(numbers[Math.floor(Math.random()*numbers.length)]), Number(numbers[Math.floor(Math.random()*numbers.length)])];
} else {
a = [Number(numbers[Math.floor(Math.random()*numbers.length)])];
}
})
.add('dynamic', function() {
var a = [];
if (Math.random() > 0.5) {
a.push(Number(numbers[Math.floor(Math.random()*numbers.length)]), Number(numbers[Math.floor(Math.random()*numbers.length)]));
} else {
a.push(Number(numbers[Math.floor(Math.random()*numbers.length)]));
}
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment