神刀安全网

JS, creating a new array using the new keyword vs. literal

I came across this small tidbit at work and I wanted to share it here.

Creating new arrays is a common thing when working in javascript so I was pleasantly surprised that there is a speed difference between the new Array() method and just instantiating an array using the [] literal.

The following are some screenshots of what the results are from this page: http://jsperf.com/new-keyword-versus-literal

JS, creating a new array using the new keyword vs. literal

After seeing the results, it’s clear that the [] should be used but I was curious why this happens so I started looking around StackOverflow to see if someone has a good explanation of what’s happening.

The first reason why new Array() is slower is because it is overloaded with multiple possibilities code paths.

JS, creating a new array using the new keyword vs. literal

This answer is insightful to see what the difference is when creating an array.

For example:

var a = new Array();   var b = []; // both are same  // difference var c = new Array(2); // [undefined × 2]   var d = [2]; // [2]  // correct but beware var e = new Array(1, 2); // [1,2]   var f = [1, 2]; // [1,2]   

This is the only difference I could think of when passing in a single integer argument. While passing multiple integers passes them as values for each item in the array.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » JS, creating a new array using the new keyword vs. literal

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮