Created
March 2, 2016 04:26
-
-
Save cicorias/ee71c1f90f72d5a7db3e to your computer and use it in GitHub Desktop.
benchmark of custom indexof vs. a map
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
'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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment