for loop vs. while loop performance

View: New views
2 Messages — Rating Filter:   Alert me  

for loop vs. while loop performance

by Alexander Koppelhuber :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

a simple loop with N loops with "for" is (in my opinion) extremely slow.
When you use "for (ii <- 0 until N)" as a (visually obvious) replacement
for
"for (ii = 0; ii < N;ii++)" in java, it is much slower than doing the same
loop with "while". Using 2 simple test programs and a decompiler it shows
that the while loop gets translated into a simple java while loop, whereas
the for loop results in a Range object and a class for the body of the loop
that gets created and called in Range.foreach.
It is clear to me that the for loop can be used in a more general (very
poweful) way for other problems, but for a simple loop it is too slow.

The following two test programs (with an extremely high loop count)
resulted in about 16000 ms for the for loop and 120 ms for the while loop:

class WhileLoop {
    val start = System.currentTimeMillis
    var ii = 0
    while (ii < 1000000000) {
      ii += 1
    }
    Console println "time: "+(System.currentTimeMillis - start)+" msec"
}

object WhileLoopPerformance {
    def main(args : Array[String]) : Unit = {
        new WhileLoop
    }
}

class ForLoop {
    val start = System.currentTimeMillis
    for (ii <- 0 until 1000000000) {
     
    }
    Console println "time: "+(System.currentTimeMillis - start)+" msec"
}

object ForLoopPerformance {
    def main(args : Array[String]) : Unit = {
        new ForLoop
    }
}

I think this performance pitfall should be mentioned somewhere. Or the
compiler detects such simple loops and translates them into a normal
java for loop.

Regards, Alex

Re: for loop vs. while loop performance

by Ismael Juma :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Mon, 2009-12-07 at 15:58 +0100, Alexander Koppelhuber wrote:
> I think this performance pitfall should be mentioned somewhere. Or the
> compiler detects such simple loops and translates them into a normal
> java for loop.

See:

https://lampsvn.epfl.ch/trac/scala/ticket/1338

Best,
Ismael