开发者

Shortened syntax wastes memory?

I found that a neat way to convert an array-like object (e.g. NodeList, Arguments) into a real array is to use:

Array.prototype.slice.call(...);

Then, I thought of a way to shorten this syntax:

[].slice.call(...);

Would the latter method waste time and/or memory by creating a new array each time that it is called? Should I avoid this syntax in complexity-essential ap开发者_如何转开发plications, or do JavaScript engines optimise this out?


I would think the [] notation probably should be avoided. If you want to save space, why not just do:

// Once in JS
var slice = Array.prototype.slice.call;

// Many places in JS
slice(...);


Personally, I don't see a major problem with using your shortened syntax. Any performance impact would be minimal (and some engines will optimise accordingly anyway) so it boils down to a personal preference. There are a couple of alternatives available to you, though. For example, you could use the ECMAScript 5th edition Function.prototype.bind to shorten it to anything you want:

var sl = Function.prototype.call.bind(Array.prototype.slice);
var myArr = sl([1, 2, 3], 1);
//-> [ 2, 3 ]

And of course, bind can be implemented in unsupporting browsers.

In supported browsers/environments, you might also be able to use Array.from or the spread operator for achieving the same results:

// Array.from works with any iterable or array-like object
var myArr = Array.from(arrayLike);

// Spread operator works only with iterables:
var myArr = [ ...arrayLike ];

If you're using a transpiler such as Traceur or Babel, these are already supported.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜