Tuesday 30 October 2012

Want to do maths? You are 120x better off with Scala than Perl

To be honest, I did expect some difference in performance between statically typed Scala (JVM-based language) and dynamic Perl... but maybe not that big. Anyway, check it out.

Here is a very simple way to compute prime numbers:

==== PrimeNumbers.scala
object PrimeNumbers {
   def isPrime(n: Int): Boolean = (2 until n) forall (d => n % d != 0)
 
   def main(args: Array[String]): Unit = {
    (8999999 until 8999999+200).map(x => if (isPrime(x)) print(x+" ") )
   }
}

==== prime_numbers.pl
sub isPrime {
    my $n = shift;
    grep( $n % $_ == 0, (2..($n-1))) ? 0 : 1
}

for(8999999..(8999999+200)) {
    isPrime($_) && print "$_\n"
}


time scala PrimeNumbers
9000011 9000041 9000049 9000059 9000067 9000119 9000127 9000143 9000163 9000193
real    0m3.187s

time perl prime_numbers.pl
real    6m23.221s

Really? This huge JVM-bloated Scala is about 120x faster in such things than Perl... can't belive!

(Perl v5.14.2, Scala 2.9.1)