缩短语法会浪费内存吗?

发布于 2024-09-24 03:53:54 字数 280 浏览 0 评论 0原文

我发现将类似数组的对象(例如 NodeList、Arguments)转换为真正的数组的一种巧妙方法是使用:

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

然后,我想到了一种缩短此语法的方法:

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

后一种方法会浪费时间和/或内存吗每次调用时创建一个新数组?我应该在复杂性至关重要的应用程序中避免使用这种语法,还是 JavaScript 引擎会对此进行优化?

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 applications, or do JavaScript engines optimise this out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

宛菡 2024-10-01 03:53:54

我认为可能应该避免使用 [] 符号。如果你想节省空间,为什么不这样做:

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

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

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(...);
轻许诺言 2024-10-01 03:53:54

就我个人而言,我不认为使用缩短的语法有什么大问题。任何性能影响都是最小的(并且某些引擎无论如何都会相应优化),因此它归结为个人喜好。不过,您还有几种选择。例如,您可以使用 ECMAScript 第 5 版 Function.prototype.bind 将其缩短为您想要的任何内容:

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

当然,bind 可以在不支持的浏览器中实现

在支持的浏览器/环境中,您也许还可以使用 Array.from扩展运算符可实现相同的结果:

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

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

如果您使用的是 Traceur 或 Babel 等转译器,则它们已受支持。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文