缩短语法会浪费内存吗?
我发现将类似数组的对象(例如 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为可能应该避免使用
[]
符号。如果你想节省空间,为什么不这样做:I would think the
[]
notation probably should be avoided. If you want to save space, why not just do:就我个人而言,我不认为使用缩短的语法有什么大问题。任何性能影响都是最小的(并且某些引擎无论如何都会相应优化),因此它归结为个人喜好。不过,您还有几种选择。例如,您可以使用 ECMAScript 第 5 版
Function.prototype.bind
将其缩短为您想要的任何内容:当然,
bind
可以在不支持的浏览器中实现。在支持的浏览器/环境中,您也许还可以使用
Array.from
或 扩展运算符可实现相同的结果:如果您使用的是 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: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:If you're using a transpiler such as Traceur or Babel, these are already supported.