Skip to content

Instantly share code, notes, and snippets.

@Tom910
Last active February 27, 2017 15:45
Show Gist options
  • Save Tom910/a42e5129778872a3cf1448513e781836 to your computer and use it in GitHub Desktop.
Save Tom910/a42e5129778872a3cf1448513e781836 to your computer and use it in GitHub Desktop.
var Benchmark = require('benchmark');
var expect = require('expect');
var suite = new Benchmark.Suite;
var test = [];
for (var s = 0; s < 1000000; s++) {
test.push(s);
}
suite
.add('binary search', () => binarySearch(test, 689123))
.add('normal search', () => normalSearch(test, 689123))
.on('cycle', event => console.log(String(event.target)))
.on('complete', function() {console.log('Fastest is ' + this.filter('fastest').map('name'))})
.run({ 'async': true });
function binarySearch(arr, value) {
var start = 0;
var end = arr.length - 1;
var point;
while(start <= end) {
point = (end + start) >> 1;
if (arr[point] === value) {
return arr[point];
}
if (arr[point] > value) {
end = point - 1;
} else if (arr[point] < value) {
start = point + 1;
}
}
}
function normalSearch(arr, value) {
return arr.find(item => item === value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment