Skip to content

Instantly share code, notes, and snippets.

@zeyangl
Last active May 13, 2019 11:42
Show Gist options
  • Save zeyangl/8130762 to your computer and use it in GitHub Desktop.
Save zeyangl/8130762 to your computer and use it in GitHub Desktop.
iteration/access pattern performance tests.
// test data
var array = [];
var dict = {};
var max = 1000000;
for(var i=0; i<max; i++)
{
array[i] = i;
dict[i] = i;
}
// tests
function testForInOnArray()
{
for(var x in array)
{
array[x] = array[x] * 2;
}
}
function testForInOnDict()
{
for(var x in dict)
{
if(dict.hasOwnProperty(x))
dict[x] = dict[x] * 2;
}
}
function testForOnArray()
{
for(var x=0; x < array.length; x++)
array[x] = array[x] * 2;
}
function testForOnArrayWithCache()
{
for(var x=0, l = array.length; x < l; x++)
array[x] = array[x] * 2;
}
function testMapIterator()
{
var iterator = map.entries();
var entry;
while ((entry = iterator.next()) !== null) {
entry[1] = entry[1] * 2;
}
}
function timeFunc(testFunc)
{
var start = +new Date();
testFunc();
var end = +new Date();
console.log("\ttime: " + (end - start));
}
console.log("array test. for in loop: ")
timeFunc(testForInOnArray);
console.log("array test. for loop: ")
timeFunc(testForOnArray);
console.log("array test. for loop with length cache: ")
timeFunc(testForOnArrayWithCache);
console.log("dict test. for in: ")
timeFunc(testForInOnDict);
@zeyangl
Copy link
Author

zeyangl commented Dec 26, 2013

array test. for in loop:
time: 339
array test. for loop:
time: 4
array test. for loop with length cache:
time: 3
dict test. for in:
time: 509

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment