Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Splice faster than Shift + Pop? Why?

I've heard from some nonspecific sources that using a combination of shift() and pop() is faster than using splice(). I haven't run a benchmark test yet and will most likely not for a while since I'm out of town, but is this true, and if so, why?

like image 868
David Avatar asked Dec 02 '25 06:12

David


1 Answers

If you don't need to retain the order of your Array, using .pop() is much, much faster than .splice().

.splice() will remove an element at a given index. What happens then is that every other element in the array after that one will need to have its position in the array reduced by 1. This can be slow if your array is large and the index at which you remove an element is small.

Using .pop(), you can remove this process of re-indexing everything entirely. Instead of removing an element at a given index, you can use .pop() to remove the last item from the array. From here, all you need to do is replace the item you want to remove with the one you got from using .pop(). As mentioned, this will of course mean that the order of your elements is not maintained.

Code examples:

.splice():

var list:Array = [0,1,2,3,4,5];
list.splice(2, 1);

trace(list); // 0,1,3,4,5

And then .pop():

var last:* = list.pop();
list[2] = last;

trace(list); // 0,1,5,4 - Notice we move 5 to the index 2 and lose the order.

And here we have the all-important actual performance tests:

var list:Array = [];
function fillList():void
{
    for(var i = 0; i < 200000; i++) list.push(i);
}


function emptyViaSplice():void
{
    fillList();
    var t:Number = getTimer();

    while(list.length > 0)
    {
        list.splice(0, 1);
    }

    trace("emptyViaSplice: " + (getTimer() - t));
}


function emptyViaPop():void
{
    fillList();
    var t:Number = getTimer();

    while(list.length > 0)
    {
        if(list.length == 1) list.pop();
        else
        {
            var l:* = list.pop();
            list[0] = l;
        }
    }

    trace("emptyViaPop: " + (getTimer() - t));
}

The results:

emptyViaSplice(); // 12153 ms
emptyViaPop(); // 37 ms
like image 107
Marty Avatar answered Dec 05 '25 09:12

Marty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!