11

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)
)
4
  • Good question. I wonder if 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.) Commented May 24, 2013 at 21:39
  • Also, doesn't the 2nd form creates an additional anonymous type for the lambda with an additional call? Is this also case with the 1st form or can it elide another function/method call? It might be worthwhile to throw things.foreach(doSome) (or doSome _ if it happens to be a method) into the mix for comparison .. Commented May 24, 2013 at 21:42
  • 1
    You know, you could just try both and diff the class files.
    – djechlin
    Commented May 24, 2013 at 21:45
  • @user2246674 That wasn't aimed at you; it was aimed at OP, which should be clear since no @ tag. And more users knowing how to do more things independently is more properly the point of SO than more questions on SO.
    – djechlin
    Commented May 24, 2013 at 21:47

4 Answers 4

15

They are identical. Given

class Foreach {
  val things = List(1,2,3)
  def doSome(i: Int) { println(i) }
  def one { for (thing <- things) { doSome(thing) } }
  def two { things.foreach{ thing => doSome(thing) } }
}

the bytecode is

public void one();
  Code:
   0:   aload_0
   1:   invokevirtual   #40; //Method things:()Lscala/collection/immutable/List;
   4:   new #42; //class Foreach$$anonfun$one$1
   7:   dup
   8:   aload_0
   9:   invokespecial   #46; //Method Foreach$$anonfun$one$1."<init>":(LForeach;)V
   12:  invokevirtual   #52; //Method scala/collection/immutable/List.foreach:(Lscala/Function1;)V
   15:  return

public void two();
  Code:
   0:   aload_0
   1:   invokevirtual   #40; //Method things:()Lscala/collection/immutable/List;
   4:   new #55; //class Foreach$$anonfun$two$1
   7:   dup
   8:   aload_0
   9:   invokespecial   #56; //Method Foreach$$anonfun$two$1."<init>":(LForeach;)V
   12:  invokevirtual   #52; //Method scala/collection/immutable/List.foreach:(Lscala/Function1;)V
   15:  return
1
  • Thanks Rex, thats great! I appreciate it. Commented May 25, 2013 at 13:14
10

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. Ranges), 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.

1
1

Per scala-lang.org:

As always, for-expressions can be used as an alternate syntax for expressions involving foreach, map, withFilter, and flatMap, so yet another way to print all elements returned by an iterator would be:

for (elem <- it) println(elem)

"Alternate syntax" would mean identical.

4
  • @user2246674 if you find details with a devil in them, submit a bug report to the team responsible for scala's documentation, because the language is clear.
    – djechlin
    Commented May 24, 2013 at 21:46
  • a more up to date version of the linked doc can be found on the new docs.scala-lang.org website: docs.scala-lang.org/overviews/collections/iterators.html Commented May 24, 2013 at 21:46
  • I would be shocked if you compiled the classes with the same everything (var names) and the classes would be equal. I bet there will be a difference.
    – Adam Gent
    Commented May 24, 2013 at 21:47
  • @AdamGent then do so and post as a separate answer. Would also recommend submitting a bug report to scala team.
    – djechlin
    Commented May 24, 2013 at 21:48
-1

Basically

a for loop is a construct that says

perform this operation n. times

a foreach loop is a construct that says

perform this operation against each value/object

1
  • Not so. Read the other answers to get a better understanding of why for isn't really a loop (it's a "for comprehension") and it can also be used "against each value/object".
    – jwvh
    Commented Mar 20, 2019 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.