Why is this Java program 1000 times faster than its Ada equivalent?

  • A+
Category:Languages

I have two programs that simply loop a billion times and increment an integer. I am timing both of the operations and comparing the two results. For the Ada program, I am using the GNAT FSF compiler. Both programs are run on Windows. I have also tried running multiple of each code and averaging the measured duration, which shows the same result.

There are two things that I expect are happening, either my Ada program is not written properly (I am very new to the language), or that it is written properly, but the Java compiler is doing something to the code that I am not aware of.

Here is the Ada program:

with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar; use Ada.Calendar;  procedure Main is     c : Integer := 1;      startTime, endTime : Time;     milliS : Duration; begin     startTime := Clock;     while c <= 1000000000 loop         c := c + 1;     end loop;      endTime := Clock;     milliS := (endTime - startTime) * 1000;      put_line("Runtime = " & Duration'Image(milliS) & " milliseconds."); end Main; 

and the Java code:

public class Test {      public static void main(String[] args) {         int c = 1;         long start = System.nanoTime();          while (c<=1000000000) {             c = c + 1;         }          long stop = System.nanoTime();          float duration = (float) ((start - stop)/1000000.0);         System.out.println(duration);     } } 

Ada compiles straight to machine code, so I expected it to be faster than the Java program.

 


The Java JIT compiler is smart enough to realize that the loop can be optimized away. And it does that.

If you modified the Java version to print out the value of c right at the end, you would get an execution time that is roughly comparable to the Ada version. If the value for c is used, the loop can't be optimized away1.

Ada compiles straight to machine code, so I expected it to be faster than the Java program.

The Java JIT compiler compiles to machine code too, but not immediately.


1 - Until we get a omniscient JIT compiler that realizes that we don't pay any attention to the output :-)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: