Scala for (i <- 0 to n) : nice but slow

I was playing around with prime numbers when I noticed that one of the implementations was several times faster than the other one.

Benchmarking the two implementations soon showed that the differences lies mainly in using the nicer

for (i <- 0 to count) {
  // does something here

instead of the uglier

var i = 0
while (i < count) {
  // does something here
  i += 1

Here the benchmark results for the two loops (running on a 2.7 GHz Intel i7):

Benchmark results of for(i

Looks like the for loop is about 8 times slower than the while loop.

I will still use the for loop where speed does not matter, since it is more concise, but where speed matters I will use the while loop until further notice.

This entry was posted in Development, Scala. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *