Using the push method or .length when adding to array?

后端 未结 6 1832
慢半拍i
慢半拍i 2020-12-31 08:26

What are the downsides to doing:

var myArray = [];
myArray[myArray.length] = val1;
myArray[myArray.length] = val2;

instead of:



        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 08:38

    As I tested, the first way is faster, I'm not sure why, keep researching. Also the ECMA doesn't mentioned which one is better, I think it is depending on how the browser vendor implements this.

    var b = new Array();
    var bd1 = new Date().getTime();
    for(var i =0;i<1000000; i++){
        b[b.length] = i;
    };
    
    alert(new Date().getTime()- bd1);
    
    var a = new Array();
    var ad1 = new Date().getTime();
    for(var i =0;i<1000000; i++){
        a.push(i);
    };
    
    alert(new Date().getTime()- ad1);
    

提交回复
热议问题