Timing arrays vs objects
HTML
<button id="btnObjs">Test Objects</button>
<button id="btnArrs">Test Arrays</button>
<div id="averages"></div>
<div id="output"></div>
JavaScript
jQuery(function($) {
var startTime, totalTime,
tmpName, tmpCoolness, tmpStrength,
i = 0, out = "",
$output = $('#output'), $averages = $('#averages'),
iterations = 2,
objTestCount = 0, arrTestCount = 0,
objTestTotalTime = 0, arrTestTotalTime = 0;
function testObj() {
startTime = new Date();
var objs = [];
for(i = 0; i < iterations; i++) {
objs.push({name: "John Doe", coolness: 84, strength: 5});
}
for(let k = 0; k<1000000; k++){
for(i = 0; i < iterations; i++) {
tmpName = objs[i]["name"];
tmpCoolness = objs[i]["coolness"];
tmpStrength = objs[i]["strength"];
}
}
totalTime = new Date() - startTime;
objTestTotalTime += totalTime;
objTestCount++;
log( "Object: " + totalTime );
}
function testArr() {
startTime = new Date();
var arrs = [];
for(i = 0; i < iterations; i++) {
arrs.push(["John Doe", 84, 5]);
}
for(let k = 0; k<1000000; k++){
for(i = 0; i < iterations; i++) {
tmpName = arrs[i][0];
tmpCoolness = arrs[i][1];
tmpStrength = arrs[i][2];
}
}
totalTime = new Date() - startTime;
arrTestTotalTime += totalTime;
arrTestCount++;
log( "Array: " + totalTime );
}
function log(msg) {
$output.html( msg + "<br />" + $output.html() );
$averages.html('<h3>Averages:</h3>'
+ '<p>Objects (' + objTestCount + '): ' + (objTestTotalTime/objTestCount) + '<br />'
+ 'Arrays (' + arrTestCount + '): ' + (arrTestTotalTime/arrTestCount) + '</p><hr />');
}
$('#btnObjs').click( testObj );
$('#btnArrs').click( testArr );
});