Skip to content

Instantly share code, notes, and snippets.

@a2800276
Created September 29, 2010 14:32
Show Gist options
  • Save a2800276/602847 to your computer and use it in GitHub Desktop.
Save a2800276/602847 to your computer and use it in GitHub Desktop.
function bench (lmbd) {
var i = 0,
start = new Date().getTime()
while (i!=10000) {
lmbd()
++i
}
return new Date().getTime() - start
}
var arr = new Array(1000)
arr.forEach( function (e, i, arr) {
arr[i] = i
})
console.log("Warmup : "+bench(function() {
var sum = 0
arr.forEach( function(e) {
sum += e
})
}))
console.log("length cached : "+bench(function() {
var sum = 0
for (var i = 0, len = arr.length; i < len; i++) {
sum += arr[i]
}
}))
console.log("length not cached : "+bench(function() {
var sum = 0
for (var i = 0; i < arr.length; i++) {
sum += arr[i]
}
}))
console.log("length not cached comp w/ != : "+bench(function() {
var sum = 0
for (var i = 0; i != arr.length; i++) {
sum += arr[i]
}
}))
console.log("length not cached preinc : "+bench(function() {
var sum = 0
for (var i = 0; i < arr.length; ++i) {
sum += arr[i]
}
}))
console.log("forEach : "+bench(function() {
var sum = 0
arr.forEach( function(e) {
sum += e
})
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment