Why is pop faster than shift?

前端 未结 6 1741
情深已故
情深已故 2020-12-01 11:46

Douglas Crockford, in JavaScript: The Good Parts, states that \"shift is usually much slower than pop\". jsPerf confirms this. Does anyone know why this is the case

6条回答
  •  半阙折子戏
    2020-12-01 12:26

    I was doing some tests on this with node (which uses chrome v8) and noticed that for arrays up to around 120k elements the performance of shift is pretty close to pop. Once you get bigger than 120K it seems to slow down dramatically.

    var sum;
    var tests = [125000,130000];
    
    console.log(JSON.stringify(process.versions));
    
    tests.forEach(function(count) {
        console.log('Testing arrays of size ' + count);
        var s1 = Date.now();
        var sArray = new Array(count);
        var pArray = new Array(count);
        for (var i = 0; i < count ; i++) {
          var num = Math.floor(Math.random() * 6) + 1
          sArray[i] = num;
          pArray[i] = num;
        }
        console.log(' -> ' + (Date.now() - s1) + 'ms: built arrays with ' + count + ' random elements');
    
        s1 = Date.now();
        sum = 0;
        while (pArray.length) {
          sum += pArray.pop();
        }
        console.log(' -> ' + (Date.now() - s1) + 'ms: sum with pop() ' + count + ' elements, sum = ' + sum);
    
        s1 = Date.now();
        sum = 0;
        while (sArray.length) {
          sum += sArray.shift();
        }
        console.log(' -> ' + (Date.now() - s1) + 'ms: sum with shift() ' + count + ' elements, sum = ' + sum);
    });
    

    Output:

    {"http_parser":"1.0","node":"0.10.22","v8":"3.14.5.9","ares":"1.9.0-DEV","uv":"0.10.19","zlib":"1.2.3","modules":"11","openssl":"1.0.1e"} 
    Testing arrays of size 125000
    -> 14ms: built arrays with 125000 random elements
    -> 2ms: sum with pop() 125000 elements, sum = 436673
    -> 6ms: sum with shift() 125000 elements, sum = 436673 
    Testing arrays of size 130000
    -> 50ms: built arrays with 130000 random elements
    -> 1ms: sum with pop() 130000 elements, sum = 455971
    -> 54372ms: sum with shift() 130000 elements, sum = 455971
    

提交回复
热议问题