//
// In this test we'll loop over an array n times, where n is the number
// of element in that array.
//
// We'll test two different methods of getting the limit in the for loop,
// A: we call arr.length at each iteration
// B: we write arr.length in a second variable at for-initialization time
//
// Number of test runs:
var ROUNDS = 5;
// Number of elements to loop over:
var ARRAY_SIZE = 500000;
function arrayLengthInForLoopPerformance() {
var arr = [];
for (var i = 0; i < ARRAY_SIZE; i++) {
arr.push('String or something');
}
// Check arr.length on each iteration
var startA = performance.now();
for (var i = 0; i < arr.length; i++) {
;
}
var stopA = performance.now();
// Check arr.length only at initialization:
var startB = performance.now();
for (var i = 0, j = arr.length; i < j; i++) {
;
}
var stopB = performance.now();
var diffA = stopA - startA;
var diffB = stopB - startB;
var diff = diffA - diffB;
diff += (diff > 0) ? ' -> B wins' : (diff < 0) ? ' -> A wins' : ' -> match';
diff = '<br/>Difference: ' + diff;
document.getElementById('results').innerHTML += 'A: ' + diffA + ', B: ' + diffB + diff + '<br/><br/>';
}
(function(count) {
document.getElementById('results').innerHTML += (ROUNDS - count + 1) + '/' + ROUNDS + ': array.length performance<br/>';
arrayLengthInForLoopPerformance();
// Recall test ROUNDS - 1 times
if (count > 1) {
var caller = arguments.callee;
window.setTimeout(function() {
caller(--count);
}, 200);
}
})(ROUNDS);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.