benchmark of custom indexof vs. a map
'use strict';
// var fast = require('fast.js');
var Benchmark = require('benchmark');
function generateString(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%^&*()-_+=!@~<>?/.,[]}{\|}";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var things = new Array(10000);
var lookups = new Array(100);
for (var i = 0, j = 0; i < things.length; i++) {
things[i] = generateString(40);
//console.log(things[i]);
if ((i % 100) === 0) {
lookups[j] = things[i];
j++;
}
}
function fastIndexOf (subject, target, fromIndex) {
var length = subject.length,
i = 0;
if (typeof fromIndex === 'number') {
i = fromIndex;
if (i < 0) {
i += length;
if (i < 0) {
i = 0;
}
}
}
for (; i < length; i++) {
if (subject[i] === target) {
return i;
}
}
return -1;
};
function mapIt(source, match, key) {
return source.map(function (el) {
// if (el[key])
// return el[key];
// else
return el;
}).indexOf(match);
}
console.log('done prep');
var suite = new Benchmark.Suite;
var count = 0;
suite.add('fastindexof', function () {
for (var i = 0; i < lookups.length; i++) {
var found = fastIndexOf(lookups, lookups[i]);
if (~found) count++;
}
})
.add('mapit', function () {
count = 0;
for (var i = 0; i < lookups.length; i++) {
var found = mapIt(lookups, lookups[i]);
if (~found) count++;
}
})
.on('cycle', function (event) {
console.log(String(event.target));
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
console.log('done again');