stacks: push vs unshift

JavaScript performance comparison

Test case created by Kyle Simpson

Info

Testing if push/pop or unshift/shift are faster for managing a "stack" in an array

Preparation code

<script>
var stack_1 = [],
        stack_2 = []
;

function push_1(item) {
        stack_1.push(item);
}

function pop_1(item) {
        return stack_1.pop();
}

function top_1() {
        return stack_1[stack_1.length-1];
}

function push_2(item) {
        stack_2.unshift(item);
}

function pop_2(item) {
        return stack_2.shift();
}

function top_2() {
        return stack_2[0];
}

function test_1() {
        var i, tmp;

        tmp = top_1();
        for (i=0; i<995; i++) {
                if (i % 5 === 0) {
                        tmp += (pop_1() / pop_1());
                }
                push_1(tmp / top_1());
        }

        tmp = 0;
        while (stack_1.length) {
                tmp += pop_1();
        }

        return tmp;
}

function test_2() {
        var i, tmp;

        tmp = top_2();
        for (i=0; i<995; i++) {
                if (i % 5 === 0) {
                        tmp += (pop_2() / pop_2());
                }
                push_2(tmp / top_2());
        }

        tmp = 0;
        while (stack_2.length) {
                tmp += pop_2();
        }

        return tmp;
}

</script>
<script>
Benchmark.prototype.setup = function() {
    var i, tmp;
   
    stack_1.length = 0;
    stack_2.length = 0;
   
    // seed both "stacks"
    for (i=0; i<5; i++) {
        tmp = Math.random();
        push_1(tmp);
        push_2(tmp);
    }
   
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
push/pop
test_1();
pending…
unshift/shift
test_2();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment