The Efficiency of Java and C++, Revisited
A number of people worked on replicating the results and optimizing the programs I listed in my earlier blog entry.
George Zervas profiled the program, found it was spending a lot of time garbage collecting, and used the -XX:+AggressiveHeap java runtime switch, which, according to its documentation
This option instructs the JVM to push memory use to the limit: the overall heap is more than 3850MB, the allocation area of each thread is 256K, the memory management policy defers collection as long as possible, and (beginning with J2SE 1.3.1_02) some GC activity is done in parallel.He also used Pentium-specific optimization switches on the C++ code, so he can not be accused of being unfair. George thus managed to bring down the execution time slowdown from 200% to 50%.
The following diagram illustrates the results he obtained:
Vassileios Karakoidas, tried a different approach, storing the numbers into an ArrayList, moving them into a native array, and sorting them in place. This brings down the slowdown to 25%.
public class SortInt {
public static void main(String args[]) {
ArrayList<RInteger> s = new ArrayList<RInteger>();
int i;
int rand = 10;
for (i = 0; i < 1000000; i++) {
s.add(new RInteger(rand));
rand = rand * 1103515245 + 12345;
}
RInteger[] rint = (RInteger[])s.toArray(new RInteger[0]);
Arrays.sort(rint);
int length = rint.length;
for (i = 0;i < length; i++)
if (i % 100000 == 0)
System.out.println(rint[i]);
}
}
Another optimization I tried involves using native integers or the Integer class in Java. Both appear to be more efficient, but, again, the program differs in the abstraction mechanisms used over its C++ sibling.
Read and post comments