mrspoonzy at gmail Cube by Noah Ellman A powerful javascript toolkit, in research © by Noah Ellman

Javascript Performance Of for(;;) Loop Versus for( . . . In ) On Arrays

Javascript lets you iterate through an Array in two ways.

var myArray = [1,2,3,4,5,6,7,8,9];

// For method
for( var i = 0; i < myArray.length; i++ ) {
   myArray[i] . . .
}

// For-in method
for( var i in myArray ) {
 myArray[i] . . .
}

For-in loops are convienent for the programmer. They are cleaner looking and they take fewer keystrokes to type. However, I have always avoided the for-in loop for arrays, and this seems to be the general concensus among experienced javascripters. And for good reason. . .

Why Not To Use For-in Loops With Arrays?

  • If Array.prototype is modified by a framework or by you, for-in loops will break.
  • For-in loops are as much as 25 times slower than classic for loops in all browsers

Run The Benchmark Test

Here is my code for the test

var test1, test2;
function Init() {
	test1 = document.getElementById('test1');
	test2 = document.getElementById('test2');
	window.test = [];
	for( var i = 0; i < 10000; i++ ) window.test.push(Math.random());
};

function Test1() {
	var a = window.test;
	var sum = 0;
	for( var i = 0; i < a.length; i++ ) {
		sum += a[i];
	}
	return sum;
	
};

function Test2() {
	var a = window.test;
	var sum = 0;
	for( var i in a ) {
		sum += a[i];
	}
	return sum;
	

};

function StopWatch(onoff) {
	if( onoff ) {
		window.stopwatch = new Date().getTime();
		return;
	} else {
		var now = new Date().getTime();
		var ms = now - window.stopwatch;
		return ms;
	}
};

function RunTest(btn) {
	var i,ms,r, btn = document.getElementById('runbtn');
	btn.oldvalue = btn.value;
	btn.value = "Running...";
	setTimeout(RunTest1,250);
};
function RunTest1() {
	var i,r,ms;
	StopWatch(true);
	for( i = 0; i < 10; i++ ) {
		r = Test1();
	}
	ms = StopWatch(false);
	test1.innerHTML = test1.innerHTML + '
' + ms + ' ms
Return: ' + r + '
' ; setTimeout(RunTest2,250); } function RunTest2() { var i,r,ms; StopWatch(true); for( i = 0; i < 10; i++ ) { r = Test2(); } ms = StopWatch(false); test2.innerHTML = test2.innerHTML + '
' + ms + ' ms
Return: ' + r + '
' ; var btn = document.getElementById('runbtn'); btn.value = btn.oldvalue; }

Discussion on /blog-javascript-foreach-performance




TheDoctor 11/05/14 :  

On this page: www.jwee.org/blog-javascript-foreach-performance you may want to change it so that the benchmark test points to /jwee/test/for-versus-forin.htm


Jwee Developer 11/05/14 :  

Doctor, I agree with you about the tooltips. They need more manual control. And yes, that hardcoded spinner2.gif is really bad.


Jwee Developer 11/05/14 :  

You want them bad? The are still in experimental mode - working perfect in FF but having some IE issues still.