Last active
May 13, 2019 11:42
-
-
Save zeyangl/8130762 to your computer and use it in GitHub Desktop.
iteration/access pattern performance tests.
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
// 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); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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