迭代性能比较
我有一个数组:
deleteIds= ["User1"];
并尝试对其进行迭代,如下所示:
第一个:
for (var index = 0; index < len; index++) {
alert(deleteIds[index]);
}
第二个:
for (var index in deleteIds) {
alert(deleteIds[index]);
}
它们的性能比较是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这充其量只是一种微观优化。除非您的
deleteIds
数组中有数十万个元素,否则您不应该考虑对此进行优化。事实证明,
for(;;;)
版本比for in
更快:http://jsperf.com/iteating-over-a-loop/2 (感谢 @Jamiec 的 jsperf)。然而,比这些代码的性能比较更重要的是,两个代码片段在功能上彼此不同(实例)。
此外,如果您向数组或数组原型链中的对象添加方法,它们将显示在
for (var x in y)
循环中,但不会显示在中for (;;;);
(现场示例):您可以使用
hasOwnProperty< /code> 消除继承的属性来自原型链,但这不会阻止您直接在对象上接收方法(实时示例) :
正是由于这些原因,不鼓励使用
for in
来迭代数组,并且for(;;;)
版本应该始终 代替使用。for in
应用于迭代对象。This is a micro optimisation at best. Unless you have hundreds of thousands of elements in your
deleteIds
array, you should not be looking at optimising this.It turns out that the
for(;;;)
version is quicker thanfor in
: http://jsperf.com/iterating-over-a-loop/2 (thanks to @Jamiec for the jsperf).However, what's more important than the performance comparison of these, is that both code snippets are functionally different to each other (live example).
Furthermore, if you add methods to either the array, or to an object in the arrays' prototype chain, they will show up in the
for (var x in y)
loop, but not infor (;;;);
(live example):You can use
hasOwnProperty
to eliminate the attributes inherited from the prototype chain, but that won't stop you receiving methods directly on the object (live example):It is because of these reasons that using
for in
for iterating over an array is discouraged, and thefor(;;;)
version should always be used instead.for in
should be used for iterating over an object.