I am a very proficient C# developer, but need to start writing code that works on the JVM. The Java language is feature poor compared to C# these days, so I was interested in t
$ javac app.java
$ scalac app.scala
$ scala HelloWorld
hello scala
ms, checksum =
1051
-100000
$ java app
hello, java
ms, checksum =
1044
-100000
What I'm doing wrong?
So, I guess I figured out the answer myself.
The problem is in the call to System.nanoTime
. Doing this has some initialization cost (loading up the Java base libraries, etc) which is much less expensive to load when called from the Java runtime than from the Scala runtime.
I prove this by changing the initial value of total, instead setting it to
var total: Long = System.nanoTime()
This is added before the first "warm up" loop, and doing so now makes both versions of the app (Java and Scala) run at the same time: about 2100 for 1000000 iterations.
Thanks for your guys' help on this, I wouldn't have figured this out without your assistance.
ps: I'll leave the "accepted answer" as-is because I wouldn't have tracked this down without his help.
I've re-run your code (and increased number of cycles x1000, so to get some meaning into benchmark).
Results:
Scala: 92 ms
Java: 59 ms
You can see that Java is 30% faster.
Looking at the bytecode, I can say that two versions are almost identical - so the difference is really strange (the bytecode listing is quite long, so I won't post it here).
Increasing the count x10000 gives this:
Scala: 884 ms
Java: 588 ms
Since the results are fairly stable, there should be some constant factor lurking somewhere. Maybe in some parameters that "scala" runner passes to JVM?
EDIT:
My configuration:
$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)
$ scala -version
Scala code runner version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL
$ inxi -SCD
System: Host the-big-maker Kernel 2.6.35-22-generic x86_64 (64 bit) Distro Linux Mint 10 Julia
CPU: Quad core AMD Phenom II X4 965 (-MCP-) cache 2048 KB flags (lm nx sse sse2 sse3 sse4a svm)
Clock Speeds: (1) 800.00 MHz (2) 800.00 MHz (3) 800.00 MHz (4) 800.00 MHz
Disks: HDD Total Size: 750.2GB (5.8% used) 1: /dev/sda OCZ 90.0GB
2: /dev/sdb ST3500413AS 500.1GB 3: /dev/sdc ST3802110A 80.0GB
4: /dev/sdd Maxtor_6Y080M0 80.0GB