Sunday, 18 December 2011

Scala, Clojure, Java Hello World

I finally took the plunge and decided to spare some time for functional programming. As being a java engineer, I wanted to have a look at jvm compliant functional languages which are Scala and Clojure.
Scala seems to be available since 2003, although public interest raised in recent years, probably after java 1.5 release. Scala is regarded as an object oriented, functional and statically typed language. It seems Scala was designed to attract java developers from the beginning.
On the other hand, Clojure is a dynamic Lisp dialect,running on jvm. Clojure is not an object oriented language like Scala, though it is possible to achieve runtime polymorphism and interface declaration.
Scala reminds me complexity of C++, by trying to be functional and object oriented at the same time, it also introduces a new type type system which is a bit resource draining for me.
In contrast to Scala, Clojure is dynamic and does not require a static type system, most operations are done with well known vector, list, map and set data structures. Clojure gives feeling of a natural functional programming impression.
At the weekend, I wondered how a simple “Hello World” program would perform in both languages and decided to run two versions of “Hello World”.

Clojure version of Hello World
Clojure : 1.3.0
Java : Jdk 1.6.0_22
user=> (time (dotimes [_  5e4] (println "Hello World")))
"Elapsed time: 4249.292309 msecs"
nil
user=>
user=> (time (dotimes [_  5e5] (println "Hello World")))
"Elapsed time: 42021.368085 msecs"
nil
user=>

Scala version of Hello World
Scala : 2.9.0.1
Java : Jdk 1.6.0_22

val start = System.currentTimeMillis (); 
for (i <- 1 to 50000 ) {
    println ("Hello World");
}
println ("Elapsed time: " + (System.currentTimeMillis ()- start));
Elapsed time: 5135
val start = System.currentTimeMillis (); 
for (i <- 1 to 500000 ) {
    println ("Hello World");
}
println ("Elapsed time: " + (System.currentTimeMillis ()- start)); 
Elapsed time: 52589

Java version of Hello World
Java : Jdk 1.6.0_22


long start= System.currentTimeMillis();
for (int i=0; i<5e4; i++)
   System.out.println("Hello World");
System.out.println("Took " + (System.currentTimeMillis()- start)); 
Took 2809


long start= System.currentTimeMillis();
for (int i=0; i<5e5; i++)
   System.out.println("Hello World");
System.out.println("Took " + (System.currentTimeMillis()- start)); 
Took 27092


I was expecting Scala would perform better than Clojure, but results were a bit surprising for me. I knew there were some performance improvements in Clojure 1.3 regarding to numeric operations by using primitive hints, but there wasn’t any numeric operation in the hello world demo. Maybe Scala code wasn't equivalent of Clojure one.

No comments:

Post a Comment