Behind the scenes Array holds its values in two ways: a densely-packed array at the beginning and a sparsely-packed map after that. This means it can be used as a map where the keys are indexes and not take up a huge amount of wasted space. Dictionary can also have int keys. Which is faster? Today we’ll find out!

This is a performance test to read and write to Array and Dictionary with int keys:

package
{
	import flash.display.*;
	import flash.utils.*;
	import flash.text.*;
 
	public class ArrayVsDictionary extends Sprite
	{
		private var __logger:TextField = new TextField();
		private function row(...cols): void
		{
			__logger.appendText(cols.join(",")+"\n");
		}
 
		public function ArrayVsDictionary()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
 
			__logger.autoSize = TextFieldAutoSize.LEFT;
			addChild(__logger);
 
			init();
		}
 
		private function init(): void
		{
			var beforeTime:int;
			var afterTime:int;
			var i:int;
			var REPS:int = 10000000;
			var array:Array = new Array();
			var dictionary:Dictionary = new Dictionary();
			var j:int;
 
			row("Class", "Time");
 
			beforeTime = getTimer();
			for (i = REPS-1; i >= 0; --i)
			{
				array[i] = i;
			}
			afterTime = getTimer();
			row("Array (write)", (afterTime-beforeTime));
 
			beforeTime = getTimer();
			for (i = REPS-1; i >= 0; --i)
			{
				dictionary[i] = i;
			}
			afterTime = getTimer();
			row("Dictionary (write)", (afterTime-beforeTime));
 
			beforeTime = getTimer();
			for (i = REPS-1; i >= 0; --i)
			{
				j = array[i];
			}
			afterTime = getTimer();
			row("Array (read)", (afterTime-beforeTime));
 
			beforeTime = getTimer();
			for (i = REPS-1; i >= 0; --i)
			{
				j = dictionary[i];
			}
			afterTime = getTimer();
			row("Dictionary (read)", (afterTime-beforeTime));
		}
	}
}

I ran this test app in the following environment:

  • Flex SDK (MXMLC) 4.6.0.23201, compiling in release mode (no debugging or verbose stack traces)
  • Release version of Flash Player 11.4.402.265
  • 2.3 Ghz Intel Core i7
  • Mac OS X 10.8.1

And here are the results I got:

Class Time
Array (write) 403
Dictionary (write) 708
Array (read) 97
Dictionary (read) 305

Performance Graph

Array is the clear winner here: about 2x faster for writing and 3x faster for reading! This will get even better if you stick to the dense portion (generally the front) of the Array, but even in a completely sparse way you’re still going to beat Dictionary hands-down.

Spot a bug? Have a suggestion? Post a comment!