Scala-每个循环之间的差异 [英] Scala - difference between for each loops
问题描述
以下两个语句之间是否有任何区别.他们达到相同的目的,对吗?它们是否编译为相同的Java代码?它们之间是否存在性能差异?或者仅仅是偏好/可读性的问题?
Is there any difference between the two following statements. They achieve the same end, correct? Do they compile to the same Java code? Is there any performance difference between them or is it just a matter of preference/readability?
for (thing <- things) {
doSome(thing)
}
things.foreach(
thing =>
doSome(thing)
)
推荐答案
用于
理解被定义为简单的句法翻译.这非常重要,因为它允许 any 对象与 for
理解一起使用,它只需要实现正确的方法即可.
for
comprehensions are defined as simple syntactic translations. That's extremely important, because that allows any object to work with for
comprehensions, it just has to implement the right methods.
IOW:Scala语言规范指出,第一个代码段已转换为第二个代码段.因此,如果两个摘要之间存在任何差异,则将违反规范,因此会导致非常严重的编译器错误.
IOW: the Scala Language Specification says that the first snippet gets translated into the second. So, if there were any difference whatsoever between the two snippets, that would be a violation of the spec and thus a very serious compiler bug.
有人要求甚至实施某些对象的特殊处理(例如 Range
s),但是这些补丁始终被拒绝,理由是对特殊类型的特殊处理只会使那些对象受益特殊类型,而使Scala总体上更快 会使所有人受益.
Some people have asked for, and even implemented, special treatment of certain objects (e.g. Range
s), but those patches were always rejected with the argument that special treatment for special types would only benefit those special types, whereas making Scala faster in general will benefit everybody.
请注意,使用宏,可能有可能纯粹通过简单的C样式 for
循环检测 Range
上的迭代并将其转换为循环或直接执行尾递归内部函数,而无需更改规范或为编译器添加特殊大小写.
Note that with Macros, it's probably possible to detect, say, iteration over a Range
purely as a simple C style for
loop and transform that into a while
loop or a direct tailrecursive inner function, without having to change the spec or add special casing to the compiler.
这篇关于Scala-每个循环之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!