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: 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.
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.
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.
for
is capable of applying any optimizations for specific (e.g. over arrays) types. Inspect the scala -print and, if that doesn't show any differences, the bytecode. (Try arrays and non-array types.)things.foreach(doSome)
(ordoSome _
if it happens to be a method) into the mix for comparison ..