Skip to content

Instantly share code, notes, and snippets.

@JosephPecoraro
Created June 16, 2009 17:03
Show Gist options
  • Save JosephPecoraro/130774 to your computer and use it in GitHub Desktop.
Save JosephPecoraro/130774 to your computer and use it in GitHub Desktop.
// Javascript Benchmark Declaring len inside and outside of a for loop
// Populate array with 0..100
var arr = []
for (var i=0; i<1e3; ++i) { arr[i] = i; }
// Declare len outside of the for
function outfor(a) {
var len = a.length;
for (var i=0; i<len; ++i);
}
// Declare len inside of the for
function infor(a) {
for (var i=0, len=a.length; i<len; ++i);
}
// Run outfor 100000 times
(function() {
console.time("outfor");
for (var i=0; i<1e5; ++i) { outfor(arr); }
console.timeEnd("outfor");
})();
// Run infor 100000 times
(function() {
console.time("infor");
for (var i=0; i<1e5; ++i) { infor(arr); }
console.timeEnd("infor");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment