Linked lists can be much faster than AS3’s Array and Vector classes if you use them under the right circumstances. It’s been over a year and a half since I last visited the topic, but today it’s time to update my LinkedList class. Read on for the freshly-optimized code and all-new performance testing and analysis!

It’s been a while since the last linked list article and much has changed with both Flash and with me. For starters, Flash Player 10.3 is now the current version as opposed to 10.0. Yes, I updated the performance results for 10.1 and 10.2, but there was no update series for 10.3 since it followed 10.2 so quickly and without promise of AS3 optimizations. The Flex SDK has also seen two major version releases in going from 3.5a to 4.5.1. More importantly, I’ve learned more about Flash optimization in that time and have therefore implemented a few changes:

  • Improved performance by converting switch statements to if-else chains.
  • Removed redundant initialization of many integers to zero
  • Avoided activation objects by converting the performance testing app’s log function from being locally-declared to being a private field.

I also made one functional change: I consolidated sort and sortOn into a single sort that takes a sort function, much like Vector.sort. This allowed me to avoid converting the whole list to a newly-allocated Array, calling Array.sort/Array.sortOn on it, and then converting back to a linked list. This was enormously expensive and involved a lot of object allocation and garbage object creation, not to mention the hidden object allocation produced by Array.sort and Array.sortOn. Instead, I use a merge sort (ported from Simon Tatham‘s C version) to sort the linked list in place.

Lastly, there was a bug in the previous tests where the shift test wasn’t immediately followed by the unshift test due to the tests being alphabetized. This meant that the tests for slice, some, sort, sortOn, and splice were operating on a much smaller array/list than the other tests. This has been corrected.

Without further ado, here is the updated LinkedList class:

LinkedListNode
/*
The MIT License
 
Copyright (c) 2011 Jackson Dunstan
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package
{
	/**
	*   A node in a linked list. Its purpose is to hold the data in the
	*   node as well as links to the previous and next nodes.
	*   @author Jackson Dunstan
	*/
	public class LinkedListNode
	{
		public var next:LinkedListNode;
		public var prev:LinkedListNode;
		public var data:*;
		public function LinkedListNode(data:*=undefined)
		{
			this.data = data;
		}
	}
}
LinkedList
/*
The MIT License
 
Copyright (c) 2011 Jackson Dunstan
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package
{
	/**
	*   A linked list, which is a single-dimensional chain of objects called
	*   nodes. This implementation is doubly-linked, so each node has a link
	*   to the next and previous node. It's API is designed to mimic that of
	*   the top-level Array class.
	*   @author Jackson Dunstan
	*		   http://JacksonDunstan.com
	*   @author Simon Tatham (sort functionality)
	*		   http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
	*/
	public class LinkedList
	{
		public var head:LinkedListNode;
		public var tail:LinkedListNode;
		public var length:int;
 
		public function LinkedList(...values)
		{
			var len:int = this.length = values.length;
			var head:LinkedListNode = null;
			var newNode:LinkedListNode;
			var i:int;
 
			// Equivalent to Array(len)
			if (len == 1)
			{
				len = values[0];
				head = this.tail = newNode = new LinkedListNode();
				for (i = 1; i < len; ++i)
				{
					newNode = new LinkedListNode();
					newNode.next = head;
					head.prev = newNode;
					head = newNode;
				}
			}
			// Equivalent to Array(value0, value1, ..., valueN)
			else if (len > 1)
			{
				i = len-1;
				head = this.tail = newNode = new LinkedListNode(values[i--]);
				for (; i >= 0; --i)
				{
					newNode = new LinkedListNode(values[i]);
					newNode.next = head;
					head.prev = newNode;
					head = newNode;
				}
			}
			this.head = head;
		}
 
		/**
		*   Equivalent to the Array [] operator
		*   @param index Index of the element to get
		*   @return The element at the given index
		*/
		public function elementAt(index:int): *
		{
			if (index < 0)
			{
				throw new TypeError("Error #2007");
			}
			else if (index >= this.length)
			{
				return undefined;
			}
			else
			{
				var halfLength:int = this.length >> 1;
				var cur:LinkedListNode;
				var i:int;
				var j:int;
				// Element is in the first half, start at beginning
				if (index < halfLength)
				{
					while (true)
					{
						j = index - i;
						if (j == 0) return cur.data;
						else if (j == 1) return cur.next.data;
						else if (j == 2) return cur.next.next.data;
						else if (j == 3) return cur.next.next.next.data;
						else if (j == 4) return cur.next.next.next.next.data;
						else if (j == 5) return cur.next.next.next.next.next.data;
						else if (j == 6) return cur.next.next.next.next.next.next.data;
						else if (j == 7) return cur.next.next.next.next.next.next.next.data;
						else if (j == 8) return cur.next.next.next.next.next.next.next.next.data;
						else if (j == 9) return cur.next.next.next.next.next.next.next.next.next.data;
						else if (j == 10) return cur.next.next.next.next.next.next.next.next.next.next.data;
						cur = cur.next.next.next.next.next.next.next.next.next.next.next;
						i += 11;
					}
				}
				// Element is in the second half, start at the end
				else
				{
					i = this.length-1;
					cur = this.tail;
					while (true)
					{
						j = i - index;
						if (j == 0) return cur.data;
						else if (j == 1) return cur.prev.data;
						else if (j == 2) return cur.prev.prev.data;
						else if (j == 3) return cur.prev.prev.prev.data;
						else if (j == 4) return cur.prev.prev.prev.prev.data;
						else if (j == 5) return cur.prev.prev.prev.prev.prev.data;
						else if (j == 6) return cur.prev.prev.prev.prev.prev.prev.data;
						else if (j == 7) return cur.prev.prev.prev.prev.prev.prev.prev.data;
						else if (j == 8) return cur.prev.prev.prev.prev.prev.prev.prev.prev.data;
						else if (j == 9) return cur.prev.prev.prev.prev.prev.prev.prev.prev.prev.data;
						else if (j == 10) return cur.prev.prev.prev.prev.prev.prev.prev.prev.prev.prev.data;
						cur = cur.prev.prev.prev.prev.prev.prev.prev.prev.prev.prev.prev;
						i -= 11;
					}
				}
			}
		}
 
		public function concat(...args): LinkedList
		{
			var ret:LinkedList = new LinkedList();
			var newNode:LinkedListNode;
 
			// Add everything from this list
			for (var cur:LinkedListNode = this.head; cur; cur = cur.next)
			{
				newNode = new LinkedListNode(cur.data);
				newNode.prev = ret.tail;
				if (ret.tail)
				{
					ret.tail.next = newNode;
				}
				else
				{
					ret.head = newNode;
				}
				ret.tail = newNode;
			}
 
			// Add everything from args
			var list:LinkedList;
			for each (var arg:* in args)
			{
				// Lists get flattened
				if (arg is LinkedList)
				{
					list = arg;
					for (cur = list.head; cur; cur = cur.next)
					{
						newNode = new LinkedListNode(cur.data);
						newNode.prev = ret.tail;
						if (ret.tail)
						{
							ret.tail.next = newNode;
						}
						else
						{
							ret.head = newNode;
						}
						ret.tail = newNode;
					}
				}
				// No flattening for any other type, even Array
				else
				{
					newNode = new LinkedListNode(arg);
					newNode.prev = ret.tail;
					if (ret.tail)
					{
						ret.tail.next = newNode;
					}
					else
					{
						ret.head = newNode;
					}
					ret.tail = newNode;
				}
			}
			return ret;
		}
 
		public function every(callback:Function, thisObject:*=null): Boolean
		{
			var index:int;
			for (var cur:LinkedListNode = this.head; cur; cur = cur.next)
			{
				if (!callback.call(thisObject, cur.data, index, this))
				{
					return false;
				}
				index++;
			}
			return true;
		}
 
		public function filter(callback:Function, thisObject:*=null): LinkedList
		{
			var ret:LinkedList = new LinkedList();
			var index:int;
			var newNode:LinkedListNode;
			for (var cur:LinkedListNode = this.head; cur; cur = cur.next)
			{
				if (callback.call(thisObject, cur.data, index, this))
				{
					newNode = new LinkedListNode(cur.data);
					newNode.prev = ret.tail;
					if (ret.tail)
					{
						ret.tail.next = newNode;
					}
					else
					{
						ret.head = newNode;
					}
					ret.tail = newNode;
				}
				index++;
			}
			return ret;
		}
 
		public function forEach(callback:Function, thisObject:*=null): void
		{
			var index:int;
			for (var cur:LinkedListNode = this.head; cur; cur = cur.next)
			{
				callback.call(thisObject, cur.data, index, this);
				index++;
			}
		}
 
		public function indexOf(searchElement:*, fromIndex:int=0): int
		{
			var index:int;
			for (var cur:LinkedListNode = this.head; cur && index < fromIndex; cur = cur.next)
			{
				index++;
			}
			for (; cur; cur = cur.next)
			{
				if (cur.data == searchElement)
				{
					return index;
				}
			}
			return -1;
		}
 
		public function join(sep:*=","): String
		{
			if (!this.head)
			{
				return "";
			}
 
			var ret:String = "";
			for (var curNode:LinkedListNode = this.head; curNode; curNode = curNode.next)
			{
				ret += curNode.data + sep;
			}
			return ret.substr(0, ret.length-sep.length);
		}
 
		public function lastIndexOf(searchElement:*, fromIndex:int=0x7fffffff): int
		{
			var index:int = this.length-1;
			for (var cur:LinkedListNode = this.tail; cur && index > fromIndex; cur = cur.prev)
			{
				index--;
			}
			for (; cur; cur = cur.prev)
			{
				if (cur.data == searchElement)
				{
					return index;
				}
				index--;
			}
			return -1;
		}
 
		public function map(callback:Function, thisObject:*=null): LinkedList
		{
			var ret:LinkedList = new LinkedList();
			var index:int;
			var newNode:LinkedListNode;
			for (var cur:LinkedListNode = this.head; cur; cur = cur.next)
			{
				newNode = new LinkedListNode(callback.call(thisObject, cur.data, index, this));
				newNode.prev = ret.tail;
				if (ret.tail)
				{
					ret.tail.next = newNode;
				}
				else
				{
					ret.head = newNode;
				}
				ret.tail = newNode;
				index++;
			}
			return ret;
		}
 
		public function pop(): *
		{
			if (this.tail)
			{
				var ret:* = this.tail.data;
				this.tail = this.tail.prev;
				this.length--;
				return ret;
			}
			else
			{
				return undefined;
			}
		}
 
		public function push(...args): void
		{
			var numArgs:int = args.length;
			var arg:*;
			var newNode:LinkedListNode;
 
			for (var i:int; i < numArgs; ++i)
			{
				arg = args[i];
				newNode = new LinkedListNode(arg);
				newNode.prev = this.tail;
				if (this.tail)
				{
					this.tail.next = newNode;
				}
				else
				{
					this.head = newNode;
				}
				this.tail = newNode;
			}
			this.length += numArgs;
		}
 
		public function reverse(): LinkedList
		{
			var front:LinkedListNode = this.head;
			var back:LinkedListNode = this.tail;
			var temp:*;
			while (front != back && back.prev != front)
			{
				temp = front.data;
				front.data = back.data;
				back.data = temp;
 
				front = front.next;
				back = back.prev;
			}
 
			return this;
		}
 
		public function shift(): *
		{
			if (this.head)
			{
				var ret:* = this.head.data;
				this.head = this.head.next;
				this.length--;
				return ret;
			}
			else
			{
				return undefined;
			}
		}
 
		public function slice(startIndex:int=0, endIndex:int=16777215): LinkedList
		{
			var ret:LinkedList = new LinkedList();
			if (startIndex >= this.length || endIndex <= startIndex)
			{
				return ret;
			}
 
			var cur:LinkedListNode = this.head;
			var i:int;
			var newNode:LinkedListNode;
			for (; i < startIndex && cur; ++i)
			{
				cur = cur.next;
			}
			for (; i < endIndex && cur; ++i)
			{
				newNode = new LinkedListNode(cur.data);
				newNode.prev = ret.tail;
				if (ret.tail)
				{
					ret.tail.next = newNode;
				}
				else
				{
					ret.head = newNode;
				}
				ret.tail = newNode;
				cur = cur.next;
			}
			return ret;
		}
 
		public function some(callback:Function, thisObject:*=null): Boolean
		{
			var index:int;
			for (var cur:LinkedListNode = this.head; cur; cur = cur.next)
			{
				if (callback.call(thisObject, cur.data, index, this))
				{
					return true;
				}
				index++;
			}
			return false;
		}
 
		public function sort(cmp:Function): void
		{
			var p:LinkedListNode;
			var q:LinkedListNode;
			var e:LinkedListNode;
			var tail:LinkedListNode;
			var oldhead:LinkedListNode;
			var insize:int;
			var nmerges:int;
			var psize:int;
			var qsize:int;
			var i:int;
			var list:LinkedListNode = this.head;
 
			/*
			 * Silly special case: if `list' was passed in as null, return
			 * null immediately.
			 */
			if (!list)
			return;
 
			insize = 1;
 
			while (1) {
				p = list;
				oldhead = list;		       /* only used for circular linkage */
				list = null;
				tail = null;
 
				nmerges = 0;  /* count number of merges we do in this pass */
 
				while (p) {
					nmerges++;  /* there exists a merge to be done */
					/* step `insize' places along from p */
					q = p;
					psize = 0;
					for (i = 0; i < insize; i++) {
						psize++;
						q = q.next;
						if (!q) break;
					}
 
					/* if q hasn't fallen off end, we have two lists to merge */
					qsize = insize;
 
					/* now we have two lists; merge them */
					while (psize > 0 || (qsize > 0 && q)) {
 
						/* decide whether next element of merge comes from p or q */
						if (psize == 0) {
							/* p is empty; e must come from q. */
							e = q; q = q.next; qsize--;
						} else if (qsize == 0 || !q) {
							/* q is empty; e must come from p. */
							e = p; p = p.next; psize--;
						} else if (cmp(p.data,q.data) <= 0) {
							/* First element of p is lower (or same);
							 * e must come from p. */
							e = p; p = p.next; psize--;
						} else {
							/* First element of q is lower; e must come from q. */
							e = q; q = q.next; qsize--;
						}
 
						/* add the next element to the merged list */
						if (tail) {
							tail.next = e;
						} else {
							list = e;
						}
						/* Maintain reverse pointers in a doubly linked list. */
						e.prev = tail;
						tail = e;
					}
 
					/* now p has stepped `insize' places along, and q has too */
					p = q;
				}
				tail.next = null;
 
				/* If we have done only one merge, we're finished. */
				if (nmerges <= 1)   /* allow for nmerges==0, the empty list case */
				{
					this.head = list;
					return;
				}
 
				/* Otherwise repeat, merging lists twice the size */
				insize *= 2;
			}
 
			this.head = list;
		}
 
		public function splice(startIndex:int, deleteCount:int, ...values): LinkedList
		{
			var ret:LinkedList = new LinkedList();
			var cur:LinkedListNode = this.head;
			var endIndex:int = startIndex + deleteCount;
			var i:int;
			var newNode:LinkedListNode;
			for (; i < startIndex && cur; ++i)
			{
				cur = cur.next;
			}
			for (; i < endIndex && cur; ++i)
			{
				// Push current node to spliced list
				newNode = new LinkedListNode(cur.data);
				newNode.prev = ret.tail;
				if (ret.tail)
				{
					ret.tail.next = newNode;
				}
				else
				{
					ret.head = newNode;
				}
				ret.tail = newNode;
 
				// Unlink current node and move on
				cur.next = cur.next.next;
				cur.next.prev = cur;
				cur = cur.next;
			}
			this.length -= deleteCount;
			return ret;
		}
 
		public function toString(): String
		{
			if (!this.head)
			{
				return "";
			}
 
			var ret:String = "";
			for (var curNode:LinkedListNode = this.head; curNode; curNode = curNode.next)
			{
				ret += curNode.data + ",";
			}
			return ret.substr(0, ret.length-1);
		}
 
		public function toLocaleString(): String
		{
			if (!this.head)
			{
				return "";
			}
 
			var ret:String = "";
			for (var curNode:LinkedListNode = this.head; curNode; curNode = curNode.next)
			{
				ret += curNode.data + ",";
			}
			return ret.substr(0, ret.length-1);
		}
 
		public function unshift(...args): void
		{
			var numArgs:int = args.length;
			var arg:*;
			var newNode:LinkedListNode;
			for (var i:int; i < numArgs; ++i)
			{
				arg = args[i];
				newNode = new LinkedListNode(arg);
				newNode.next = this.head;
				if (this.head)
				{
					this.head.prev = newNode;
				}
				else
				{
					this.tail = newNode;
				}
				this.head = newNode;
			}
			this.length += numArgs;
		}
	}
}
package
{
	import flash.display.*;
	import flash.events.*;
	import flash.text.*;
	import flash.utils.*;
 
	/**
	*   An app to test linked list performance
	*   @author Jackson Dunstan
	*/
	public class LinkedListPerformance extends Sprite
	{
		private var logger:TextField = new TextField();
 
		private function row(...cols): void
		{
			logger.appendText(cols.join(",") + "\n");
		}
 
		public function LinkedListPerformance()
		{
			logger.autoSize = TextFieldAutoSize.LEFT;
			addChild(logger);
 
			var beforeTime:int;
			var afterTime:int;
			var arrayTime:int;
			var listTime:int;
 
			const VALUE:Object = {val:33};
			const ALTERNATE_VALUE:Object = {val:44};
			const SIZE:int = 10000;
			const ELEMENTATINDEX:int = SIZE / 2;
			const SPLICE_START:int = SIZE / 2;
			const SLICE_START:int = SIZE;
			const SLICE_END:int = SIZE;
 
			const TRAVERSES:int = 1000;
			const ELEMENTATS:int = 1000000;
			const CONCATS:int = 100;
			const EVERYS:int = 1000;
			const FILTERS:int = 100;
			const FOREACHS:int = 1000;
			const INDEXOFS:int = 1000;
			const JOINS:int = 10;
			const MAPS:int = 100;
			const PUSHPOPS:int = 100000;
			const REVERSES:int = 100;
			const SLICES:int = 100000;
			const SOMES:int = 1000;
			const SORTS:int = 10;
			const SPLICES:int = 10000;
			const UNSHIFTSHIFTS:int = 100000;
 
			var curNode:LinkedListNode;
			var i:int;
			var j:int;
 
			var array:Array;
			var list:LinkedList;
			array = [];
			list = new LinkedList();
			for (i = 0; i < SIZE; ++i)
			{
				array[i] = VALUE;
				list.push(VALUE);
			}
 
			row("Function", "Array", "Linked List");
 
			beforeTime = getTimer();
			for (j = 0; j < TRAVERSES; ++j)
			{
				for (i = 0; i < SIZE; ++i)
				{
					array[i];
				}
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (j = 0; j < TRAVERSES; ++j)
			{
				for (curNode = list.head; curNode; curNode = curNode.next)
				{
					curNode.data;
				}
			}
			listTime = getTimer() - beforeTime;
			row("traverse", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < ELEMENTATS; ++i)
			{
				array[ELEMENTATINDEX];
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < ELEMENTATS; ++i)
			{
				list.elementAt(ELEMENTATINDEX);
			}
			listTime = getTimer() - beforeTime;
			row("elementAt/[]", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < CONCATS; ++i)
			{
				array.concat(array);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < CONCATS; ++i)
			{
				list.concat(list);
			}
			listTime = getTimer() - beforeTime;
			row("concat", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < EVERYS; ++i)
			{
				array.every(arrayCallbackTrue);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < EVERYS; ++i)
			{
				list.every(listCallbackTrue);
			}
			listTime = getTimer() - beforeTime;
			row("every", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < FILTERS; ++i)
			{
				array.filter(arrayCallbackTrue);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < FILTERS; ++i)
			{
				list.filter(listCallbackTrue);
			}
			listTime = getTimer() - beforeTime;
			row("filter", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < FOREACHS; ++i)
			{
				array.forEach(arrayCallbackTrue);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < FOREACHS; ++i)
			{
				list.forEach(listCallbackTrue);
			}
			listTime = getTimer() - beforeTime;
			row("forEach", arrayTime, listTime);
 
			array[SIZE-1] = ALTERNATE_VALUE;
			beforeTime = getTimer();
			for (i = 0; i < INDEXOFS; ++i)
			{
				array.indexOf(ALTERNATE_VALUE);
			}
			arrayTime = getTimer() - beforeTime;
			array[SIZE-1] = VALUE;
			list.tail.data = ALTERNATE_VALUE;
			beforeTime = getTimer();
			for (i = 0; i < INDEXOFS; ++i)
			{
				list.indexOf(ALTERNATE_VALUE);
			}
			listTime = getTimer() - beforeTime;
			row("indexOf", arrayTime, listTime);
			list.tail.data = VALUE;
 
			beforeTime = getTimer();
			for (i = 0; i < JOINS; ++i)
			{
				array.join();
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < JOINS; ++i)
			{
				list.join();
			}
			listTime = getTimer() - beforeTime;
			row("join", arrayTime, listTime);
 
			array[0] = ALTERNATE_VALUE;
			beforeTime = getTimer();
			for (i = 0; i < INDEXOFS; ++i)
			{
				array.lastIndexOf(ALTERNATE_VALUE);
			}
			arrayTime = getTimer() - beforeTime;
			array[0] = VALUE;
			list.head.data = ALTERNATE_VALUE;
			beforeTime = getTimer();
			for (i = 0; i < INDEXOFS; ++i)
			{
				list.lastIndexOf(ALTERNATE_VALUE);
			}
			listTime = getTimer() - beforeTime;
			row("lastIndexOf", arrayTime, listTime);
			list.head.data = VALUE;
 
			beforeTime = getTimer();
			for (i = 0; i < MAPS; ++i)
			{
				array.map(arrayCallbackTrue);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < MAPS; ++i)
			{
				list.map(listCallbackTrue);
			}
			listTime = getTimer() - beforeTime;
			row("map", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < PUSHPOPS; ++i)
			{
				array.pop();
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < PUSHPOPS; ++i)
			{
				list.pop();
			}
			listTime = getTimer() - beforeTime;
			row("pop", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < PUSHPOPS; ++i)
			{
				array.push(VALUE);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < PUSHPOPS; ++i)
			{
				list.push(VALUE);
			}
			listTime = getTimer() - beforeTime;
			row("push", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < REVERSES; ++i)
			{
				array.reverse();
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < REVERSES; ++i)
			{
				list.reverse();
			}
			listTime = getTimer() - beforeTime;
			row("reverse", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < UNSHIFTSHIFTS; ++i)
			{
				array.shift();
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < UNSHIFTSHIFTS; ++i)
			{
				list.shift();
			}
			listTime = getTimer() - beforeTime;
			row("shift", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < UNSHIFTSHIFTS; ++i)
			{
				array.unshift(VALUE);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < UNSHIFTSHIFTS; ++i)
			{
				list.unshift(VALUE);
			}
			listTime = getTimer() - beforeTime;
			row("unshift", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < SLICES; ++i)
			{
				array.slice(SLICE_START, SLICE_END);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < SLICES; ++i)
			{
				list.slice(SLICE_START, SLICE_END);
			}
			listTime = getTimer() - beforeTime;
			row("slice", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < SOMES; ++i)
			{
				array.some(arrayCallbackFalse);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < SOMES; ++i)
			{
				list.some(listCallbackFalse);
			}
			listTime = getTimer() - beforeTime;
			row("some", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < SORTS; ++i)
			{
				array.sort();
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < SORTS; ++i)
			{
				list.sort(cmp);
			}
			listTime = getTimer() - beforeTime;
			row("sort", arrayTime, listTime);
 
			beforeTime = getTimer();
			for (i = 0; i < SPLICES; ++i)
			{
				array.splice(SPLICE_START, 5, VALUE, VALUE, VALUE, VALUE, VALUE);
			}
			arrayTime = getTimer() - beforeTime;
			beforeTime = getTimer();
			for (i = 0; i < SPLICES; ++i)
			{
				list.splice(SPLICE_START, 5, VALUE, VALUE, VALUE, VALUE, VALUE);
			}
			listTime = getTimer() - beforeTime;
			row("splice", arrayTime, listTime);
		}
 
		private function arrayCallbackTrue(cur:*, index:int, list:Array): Boolean
		{
			return true;
		}
 
		private function listCallbackTrue(cur:*, index:int, list:LinkedList): Boolean
		{
			return true;
		}
 
		private function arrayCallbackFalse(cur:*, index:int, list:Array): Boolean
		{
			return false;
		}
 
		private function listCallbackFalse(cur:*, index:int, list:LinkedList): Boolean
		{
			return false;
		}
 
		private function cmp(a:*, b:*): int
		{
			return a.val - b.val;
		}
	}
}

I ran the performance test with the following environment:

  • Flex SDK (MXMLC) 4.5.1.21328, compiling in release mode (no debugging or verbose stack traces)
  • Release version of Flash Player 10.3.181.34
  • 2.4 Ghz Intel Core i5
  • Mac OS X 10.6.8

And got these results:

Function Array Linked List
traverse 68 37
elementAt/[] 7 8697
concat 45 507
every 377 888
filter 83 338
forEach 370 855
indexOf 103 151
join 107 114
lastIndexOf 105 155
map 85 338
pop 2 2
push 5 32
reverse 5 109
shift 1241 2
unshift 1251 19
slice 30 16
some 3771 9078
sort 2490 1424
splice 10 216

Here are the same results in graph form:

Linked List Performance Graph

It’s much easier to see if we remove the elementAt/[] test:

Linked List Performance Graph

The old version’s result for sort showed it roughly on par with Array and sortOn was about half as fast as Array. In the new version, sort is now almost twice as fast as Array.sort! Really, the advantages are still greater as the linked list version now completely avoids object allocation (and subsequent garbage collection).

Also, for simplicity’s sake the above results do not show the old, switch-based elementAt/[]. However, it was clocking in at about 9350 milliseconds so, believe it or not, the new if-else chain version is actually about 8% faster. Considering how terrible the linked list performance is anyhow, this isn’t a big deal.

So how do linked lists fare with a new Flash Player, a new Flex SDK, a new sort function, and some miscellaneous other improvements? Well, as you can see from the above data and graphs, the results are quite mixed. Here is a table that simplifies the advantages on a function-by-function basis:

Function Best Data Structure Speedup
traverse LinkedList 2x
elementAt/[] Array 1000x
concat Array 10x
every Array 2x
filter Array 4x
forEach Array 2x
indexOf Array 50%
join –tie– n/a
lastIndexOf Array 50%
map Array 4x
pop –tie– n/a
push Array 5x
reverse Array 20x
shift LinkedList 600x
unshift LinkedList 500x
slice LinkedList 2x
some Array 3x
sort LinkedList 2x
splice Array 20x

In every case except join and pop the winner is by a large margin. It’s therefore important to keep in mind how you will be using the data structure when you decide which to go with. Doing a lot of random access by index or searching for values? Array wins by a landslide. Doing a lot of sorting or traversing? LinkedList destroys Array.

Download the LinkedList and LinkedListNode classes as a ZIP file.

Spot a bug? Have an optimization to suggest? Post a comment!