执行速度和/或内存消耗之间是否存在差异:
for (var o in objs) { ... }
和
objs.forEach((o) { ... });
最佳答案
使用列表和队列,后者在我的机器上使用 Dart VM 往往快 2 到 2.5 倍。这是有道理的,因为 forEach
使用 for (int i = 0; i < length; i++)
的一些变体在内部进行迭代, 而 for-in
迭代 Iterator.moveNext()
.
使用 dart2js
并在 d8
上运行, forEach
在我的机器上,队列大约快 1.3 倍,但列表慢 1.2 倍。
与往常一样,当性能是一个特别重要的考虑因素时,对实际代码进行基准测试是有意义的。
如果内存消耗存在显着差异,我会认为这是一个错误。
更新: Florian Loitsch 在下面的评论中解释道:
The
moveNext
method is currently not inlined (too large). This is something that should change very soon, after which both should be roughly at the same speed.
关于dart - forEach 和 for (var o in objs) 之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16753474/