Skip to content

Instantly share code, notes, and snippets.

@Tom910
Last active July 26, 2018 14:22
Show Gist options
  • Save Tom910/f7e47a406b4476afbc1431f322fa0ae5 to your computer and use it in GitHub Desktop.
Save Tom910/f7e47a406b4476afbc1431f322fa0ae5 to your computer and use it in GitHub Desktop.
var Benchmark = require('benchmark');
var expect = require('expect');
var suite = new Benchmark.Suite;
var testArray = [1,2,3,4,5,6,7,8,9,10,11,12,13];
var resultat = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26];
suite
.add('forHoley', () => forHoley(testArray))
.add('forPush', () => forPush(testArray))
.add('map', () => mapTest(testArray))
.on('cycle', event => console.log(String(event.target)))
.on('complete', function() {console.log('Fastest is ' + this.filter('fastest').map('name'))})
.run({ 'async': true });
function forHoley(array) {
var length = array.length,
result = Array(length);
for(var i = 0; i < length; i++) {
result[i] = array[i] * 2;
}
return result;
}
function forPush(array) {
var result = [];
for(var i = 0; i < array.length; i++) {
result[i] = array[i] * 2;
}
return result;
}
function mapTest(arr) {
return arr.map(function(item) {return item * 2})
}
expect(forHoley(testArray)).toEqual(resultat);
expect(forPush(testArray)).toEqual(resultat);
expect(mapTest(testArray)).toEqual(resultat);
for(var i = 0; i < array.length; i++) {
result[i] = array[i] * 2;
}
return result;
}
function mapTest(arr) {
return arr.map(function(item) {return item * 2})
}
expect(forTest(testArray)).toEqual(resultat);
expect(forSlowTest(testArray)).toEqual(resultat);
expect(mapTest(testArray)).toEqual(resultat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment