Myth Buster – Benchmarking Loops

Lets have a look at some of the most common and fastest loops used in ActionScript 3. Is int really faster than uint and Number? Is while loop faster than for? Is pre-increment faster than post-increment? To test all of these I have created benchmark test application on wonderfl. App compares loops with 10.000.000 iterations and logs testing times. To compare different variable types, loop methods, increment / decrement modes, there are buttons grouping each test. Please be patient with your first click, the model Array is being generated (Link button also generates linked list). The first test compares Arrays, second one Vectors.

Loop Benchmark Test 1 uses Array:

Loop Benchmark Test 2 uses Vector.:

Loop Benchmar Test 4: Linked List vs. Final Linked List:

To sum it up fastest seems to be these methods:

Arrays
testForUintPreDecrement: 78 ms. *GLOBAL FASTEST*
testForUintPostDecrement: 78 ms. *GLOBAL FASTEST*
testForIntPostDecrement: 78 ms. *GLOBAL FASTEST*
testWhileUintPreDecrement: 78 ms. *GLOBAL FASTEST*
testWhileUintPostDecrement: 78 ms. *GLOBAL FASTEST*

Vectors
testForUintPreDecrement: 62 ms. *GLOBAL FASTEST*
testForIntPreDecrement: 62 ms. *GLOBAL FASTEST*
testForIntPostDecrement: 62 ms. *GLOBAL FASTEST*
testWhileIntPreIncrement: 62 ms. *GLOBAL FASTEST*
testWhileIntPostIncrement: 62 ms. *GLOBAL FASTEST*
testLinked: 62 ms. *GLOBAL FASTEST*

Those are my favorits:

public function testForIntPreDecrement():void
{
	for(var i:int = R - 1; i > -1; --i)
		modelArray[i];
}

public function testWhileUintPostDecrement():void
{
	var i:uint = modelArray.length;
	while(i--)
		modelArray[i];
}

public function testLinked():void
{
	var link:Linked = firstLink;
	while(link)
		link = link.next;
}

… that says it all:

  • “for” and “while” loops can be equally fast, while “for each” loop is much slower
  • “uint” and “int” is equally fast, and is much faster than “Number”
  • “pre” vs. “post” is more less the same
  • decrement mostly wins over increment, but in some cases is equally fast
  • Linked-lists iteration performance equals to Vector and is better than Arryas
  • when casting required, linked lists rules them all
  • using ByteArray as list is not as fast as Array nor Vector

1 comment so far

  1. […] Myth Buster – Benchmarking Loops […]

Leave a comment

Please be polite and on topic. Your e-mail will never be published.