ActionScript 3 Fast array item removal


Example

If you do not require an array to be in any particular order, a little trick with pop() will afford you enormous performance gains compared to splice().

When you splice() an array, the index of subsequent elements in that array needs to be reduced by 1. This process can consume a large chunk of time if the array is large and the object you are removing is nearer the beginning of that array.

If you do not care about the order of the elements in the array, you can instead replace the item you want to remove with an item that you pop() from the end of the array. This way, the indexes of all the other items in the array remains the same and the process does not degrade in performance as the length of your array grows.

Example:

function slowRemove(list:Array, item:*):void {
    var index:int = list.indexOf(item);
    
    if (index >= 0) list.splice(index, 1);
}

function fastRemove(list:Array, item:*):void {
    var index:int = list.indexOf(item);

    if (index >= 0) {
        if (index === list.length - 1) list.pop();

        else {
            // Replace item to delete with last item.
            list[index] = list.pop();
        }
    }
}