Why push method is significantly slower than putting values via array indices in Javascript

前端 未结 3 434
攒了一身酷
攒了一身酷 2020-12-15 21:39

I pretty don\'t understand why this test :

http://jsperf.com/push-method-vs-setting-via-key

Shows that

 a.push(Math.random());
3条回答
  •  囚心锁ツ
    2020-12-15 22:03

    Because the .push() is a function call and the other is direct assignment. Direct assignment is always faster.

    Remember that in javascript, arrays are objects like everything else. This means you can assign properties directly to them.

    In the special case of arrays, they have a built-in length property that gets update behind the scenes (and lots of other optimizations under the hood, but that's not important right now).

    In a regular object, you can do this but its not an array:

    var x = {
       0: 'a',
       1: 'b',
       2: 'c'
    };
    

    However, since arrays and hashes are both objects, this is equivalent.

       var x = [
          'a',
          'b',
          'c'
       ];
    

    Since x is an array in the second case, length is automatically calculated and available.

提交回复
热议问题