pop vs shift on a array (v20)

Revision 20 of this benchmark created by Shimon Doodkin on


Description

If you can choose between a .pop() or .shift() on a Array, what would be a wise decision?

As my http://jsperf.com/adding-items-array/6 test shows the unshift is awful for performance. The same counts for .shift(), awful performance.

Setup

var array1 = new Array(50);
    for(var i=0;i<array1.length;i++)
    array1[i]=1;
    
    var array2 = new Array(50);
    for(var i=0;i<array2.length;i++)
    array2[i]={a:1};

Test runner

Ready to run.

Testing in
TestOps/sec
.pop()
var k=0;
var i = array1.length;
while (i--) {
 k=array1.pop()
 if(k==1) k=k+1
}
console.log(k);
ready
.shift()
var k=0;
var i = array1.length;
while (i--) {
 k=array1.shift()
 if(k==1) k=k+1
}
console.log(k);
ready
.splice beginning
var k=0;
var i = array1.length;
while (i--) {
 k=array1.splice(0, 1)
 if(k==1) k=k+1
}
console.log(k);
ready
for loop no array touching
var k=0;
for(i=0;i<array1.length;i++) {
 k=array1[i]
 if(k==1) k=k+1
}
console.log(k);
ready
different shift
var k=0;
while(k=array1.shift()) {
if(k==1) k=k+1
}
console.log(k);
ready
different loop
var k=0,l=array1.length;
for(i=0;i<l;i++) {
 k=array1[i]
 if(k==1) k=k+1
}
console.log(k);
ready
different pop
// only valid if you have array of objects
var k=0;
while(k=array1.pop()) {
if(k==1) k=k+1
}
console.log(k);
ready
use for instead of while
// only valid if you have array of objects or true returning values
var k=0;
for(;k=array1.shift();) {
if(k==1) k=k+1
}
console.log(k);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.