The problem in this particular case is that you return from within the for-expression. That in turn gets translated into a throw of a NonLocalReturnException, which is caught at the enclosing method. The optimizer can eliminate the foreach but cannot yet eliminate the throw/catch.
And throw/catch is expensive. But since such nested returns are rare in Scala programs, the optimizer did not yet address this case. There work going on to improve the opimizer which hopefully will solve this issue soon.
You beat me to it, but that's expected :D – juancn Jun 16 at 13:05 3 Pretty heavy that a return becomes an exception. I'm sure it's documented somewhere, but it has the reek of ununderstandable hidden magic. Is that really the only way?
– skrebbel Jun 16 at 14:13 3 If the return happens from inside a closure, it seems to be the best available option. Returns from outside closures are of course translated directly to return instructions in the bytecode. – Martin Odersky Jun 16 at 15:09 1 I'm sure I'm overlooking something, but why not instead compile the return from inside a closure to set an enclosed boolean flag and return-value, and check that after the closure-call returns?
– Luke Hutteman Jun 16 at 15:55 2 Why is his functional algorithm still 55 times slower? It doesn't look like it should suffer from such horrible performance – Elijah Jun 16 at 20:10.
The problem is most likely the use of a for comprehension in the method isEvenlyDivisible. Replacing for by an equivalent while loop should eliminate the performance difference with Java. As opposed to Java's for loops, Scala's for comprehensions are actually syntactic sugar for higher-order methods; in this case, you're calling the foreach method on a Range object.
Scala's for is very general, but sometimes leads to painful performance. You might want to try the -optimize flag in Scala version 2.9. Observed performance may depend on the particular JVM in use, and the JIT optimizer having sufficient "warm up" time to identify and optimize hot-spots. Recent discussions on the mailing list indicate that the Scala team is working on improving for performance in simple cases: http://groups.google.com/group/scala-user/browse_thread/thread/86adb44d72ef4498 http://groups.google.com/group/scala-language/browse_thread/thread/94740a10205dddd2 Here is the issue in the bug tracker: https://issues.
Scala-lang. Org/browse/SI-4633 Update 5/28: As a short term solution, the ScalaCL plugin (alpha) will transform simple Scala loops into the equivalent of while loops.As a potential longer term solution, teams from the EPFL and Stanford are collaborating on a project enabling run-time compilation of "virtual" Scala for very high performance. For example, multiple idiomatic functional loops can be fused at run-time into optimal JVM bytecode, or to another target such as a GPU.
The system is extensible, allowing user defined DSLs and transformations. Check out the publications and Stanford course notes. Preliminary code is available on Github, with a release intended in the coming months.
4 Great, I replaced the for comprehension with a while loop and it runs exactly the same speed (+/- – Rex Kerr May 27 at 2:03 7 This got me once, too. Had to translate an algorithm from using collection functions to nested while loops (level 6! ) because of incredible slow-down.
This is something that needs to be heavily targeted, imho; of what use is a nice programming style if I can not use it when I need decent (note: not blazing fast) performance? – Raphael May 27 at 18:22 6 When is for suitable then? – OscarRyz Jun 16 at 1:41 @OscarRyz - a for in scala behaves as the for ( : ) in java, for the most part.
– Mike Axiak Jun 16 at 12:28.
As a follow-up, I tried the -optimize flag and it reduced running time from 103 to 76 seconds, but that's still 107x slower than Java or a while loop. Then I was looking at the "functional" version: object P005 extends App{ def isDivis(x:Int) = (1 to 20) forall {x % _ == 0} def find(n:Int):Int = if (isDivis(n)) n else find (n+2) println (find (2)) } and trying to figure out how to get rid of the "forall" in a concise manner. I failed miserably and came up with object P005_V2 extends App { def isDivis(x:Int):Boolean = { var I = 1 while(i 20) true else if(x % I!
= 0) false else isDivis(x, i+1) def find(n:Int):Int = if (isDivis(n, 2)) n else find (n+2) println (find (2)) } So Scala's tail recursion wins the day, but I'm surprised that something as simple as a "for" loop (and the "forall" method) is essentially broken and has to be replaced by inelegant and verbose "whiles", or tail recursion. A lot of the reason I'm trying Scala is because of the concise syntax, but it's no good if my code is going to run 100 times slower! EDIT: (deleted) EDIT OF EDIT: Former discrepancies between run times of 2.5s and 0.7s were entirely due to whether the 32-bit or 64-bit JVMs were being used.
Scala from the command line uses whatever is set by JAVA_HOME, while Java uses 64-bit if available regardless. IDEs have their own settings. Some measurements here: Scala execution times in Eclipse.
1 Thanks for the thorough update. – pst May 28 at 7:17 1 the isDivis-method can be written as: def isDivis(x: Int, i: Int): Boolean = if (i > 20) true else if (x % I! = 0) false else isDivis(x, i+1).
Notice that in Scala if-else is an expression which always return a value. No need for the return-keyword here. – Antoras May 28 at 10:08.
The answer about for comprehension is right, but it's not the whole story. You should note note that the use of return in isEvenlyDivisible is not free. The use of return inside the for, forces the scala compiler to generate a non-local return (i.e.To return outside it's function).
This is done through the use of an exception to exit the loop. The same happens if you build your own control abstractions, for example: def loopT(times: Int, default: T)(body: ()=>T) : T = { var count = 0 var result: T = default while(count Since the bracketed expression is a function literal, which you can see in the signature of loop this forces the compiler to generate a non local return, that is, the return forces you to exit foo, not just the body. In Java (i.e.
The JVM) the only way to implement such behavior is to throw an exception. Going back to isEvenlyDivisible: def isEvenlyDivisible(a:Int, b:Int):Boolean = { for (i.
Some ways to speed up the forall method I discovered: The original: 41.3 s def isDivis(x:Int) = (1 to 20) forall {x % _ == 0} Pre-instantiating the range, so we don't create a new range every time: 9.0 s val r = (1 to 20) def isDivis(x:Int) = r forall {x % _ == 0} Converting to a List instead of a Range: 4.8 s val rl = (1 to 20). ToList def isDivis(x:Int) = rl forall {x % _ == 0} I tried a few other collections but List was fastest (although still 7x slower than if we avoid the Range and higher-order function altogether). While I am new to Scala, I'd guess the compiler could easily implement a quick and significant performance gain by simply automatically replacing Range literals in methods (as above) with Range constants in the outermost scope.
Or better, intern them like Strings literals in Java. Footnote: Arrays were about the same as Range, but interestingly, pimping a new forall method (shown below) resulted in 24% faster execution on 64-bit, and 8% faster on 32-bit. When I reduced the calculation size by reducing the number of factors from 20 to 15 the difference disappeared, so maybe it's a garbage collection effect.
Whatever the cause, it's significant when operating under full load for extended periods. A similar pimp for List also resulted in about 10% better performance. Val ra = (1 to 20).
ToArray def isDivis(x:Int) = ra forall2 {x % _ == 0} case class PimpedSeqA(s: IndexedSeqA) { def forall2 (p: A => Boolean): Boolean = { var I = 0 while (i.
I just wanted to comment for people who might lose faith in Scala over issues like this that these kinds of issues come up in the performance of just about all functional languages. If you are optimizing a fold in Haskell, you will often have to re-write it as a recursive tail-call-optimized loop, or else you'll have performance and memory issues to contend with. I know it's unfortunate that FPs aren't yet optimized to the point where we don't have to think about things like this, but this is not at all a problem particular to Scala.
You're missing the point completely... – Luigi Plinge Jun 16 at 22:04 The point of every performance consideration might always be a more clever way to tackle the problem as a whole, not the implementation of your solution. – user unknown Aug 20 at 22:43.
Have you tried the one-liner given in this solution: pavelfatin.com/scala-for-project-euler/ The time given is at least faster than your, though far from the while loop.. :).
It's pretty similar to my functional version. You could write mine as def r(n:Int):Int = if ((1 to 20) forall {n % _ == 0}) n else r (n+2); r(2), which is 4 characters shorter than Pavel's. :) However I don't pretend my code is any good - when I posted this question I had coded a total of about 30 lines of Scala.
– Luigi Plinge Jul 5 at 23:06.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.