I'm working on an algorithm and I've been optimizing it successfully until I came across this strange problem:
Array C is passed as an argument to the method.
int lim = C.length;
double A[]=new double[lim];
double B[]=new double[lim];
for (int I = offset; I < lim; I++) {
A[ (int) B[C[I]] ] = C[I];
}
A
, B
are double
arrays and C
is an integer array. They are all of equal size.
I noticed that this code was running much slower than it should when I found the difference in time using System.nanoTime()
.
By troubleshooting, I found that if I replace C[I]
with just I
or a constant or any variable initialized with a value embedded in the code, it runs many times faster than when it's value is coming from a source that is not predefined in the code.
As a final test, I replaced C[I]
with a random integer and got the same slow speed. What is happening? Does the JVM optimize code for predefined variables? Can I reasonably solve this problem without defining my array's contents in code (which I'm sure will solve this issue)?
If I can solve this, the optimization will produce a new sorting algorithm that will run much faster than Java 7's implementation of the QuickSort algorithm. It is already faster than it for n < 8000 or thereabouts for many kinds of input.
Currently, I have recorded it (on my machine) sorting 8 million numbers (type double) in 3.8-3.9 seconds while Java's QuickSort implementation(Arrays.sort())
does it in about 1.53 seconds on the same machine. I have tracked the slow-down to 2 incidences of this line of code in 2 for loops and I need help.