Created
May 14, 2011 04:32
-
-
Save sri/971921 to your computer and use it in GitHub Desktop.
benchmark_underscore.js
This file contains 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
#! /usr/bin/env node | |
var Underscore = require('./underscore') | |
function randomizedArray(size, limit) { | |
var result = [] | |
for (var i=0; i < size; i++) { | |
var rnd = Math.floor(Math.random() * limit) | |
result.push(rnd + '') | |
} | |
return result | |
} | |
function elapsedTime(fn) { | |
var start = Date.now() | |
var result = fn() | |
var elapsed = Date.now() - start | |
return [result, elapsed] | |
} | |
// Our implementation | |
function intersect(a, b) { | |
var obj = {} | |
for (var i=0; i < a.length; i++) { | |
obj[ a[i] ] = true | |
} | |
var both = {} | |
for (var i=0; i < b.length; i++) { | |
if (obj[ b[i] ] != null) | |
both[ b[i] ] = true | |
} | |
var result = [] | |
for (var k in both) { | |
result.push(k) | |
} | |
return result | |
} | |
function timeIntersect() { | |
var a = randomizedArray(20000, 100000) | |
var b = randomizedArray(30000, 100000) | |
var u = elapsedTime(function() { return Underscore.intersect(a, b) }) | |
var m = elapsedTime(function() { return intersect(a, b) }) | |
if (u[0].length != m[0].length) { | |
console.log("* experiment failed: u[0].length=" + u[0].length + | |
"; m[0].length=" + m[0].length) | |
} else { | |
console.log("Underscore.intersect ms: " + u[1]) | |
console.log("My.intersect ms: " + m[1]) | |
console.log("My.intersect is " + Math.floor(u[1] / m[1]) + " times faster" ) | |
} | |
} | |
timeIntersect() | |
/* | |
Underscore.intersect ms: 20835 | |
My.intersect ms: 14 | |
My.intersect is 1488 times faster | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment