Created
September 13, 2016 06:37
-
-
Save maxvipon/336d5ab739711c95bc3ed19e4b8410b8 to your computer and use it in GitHub Desktop.
Bench const array vs dynamic array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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