Java Arrays.sort () affects the performance of other methods in my program; Why?

advertisements

I am developing a java program in which I'm using a big array of instances of a Class. I have to make some calculations for every object of the array (using its Class methods). When I order the array using Arrays.Sort or other methods I notice an increment of the calculation time to perform my computations, that is excluding the time to do the sort!

If I comment the Arrays.sort function, prior to the other computation the time of calculation is about 1 or 2 milliseconds, while uncommenting it increases to 5 or 6 ms.

I have to do this work for huge number of steps (even 300,000) so the increment changes a lot my performances.

Is there any explanation for this strange behaviour?


Here's my best guess, given what little I know about the code:

Objects are usually, though not always, placed on the heap in roughly the order they are allocated. GC will move them around, but there is some chance that the order will be roughly preserved.

Then, when you access each on turn to do calculations on their data, you may end up with roughly linear memory access. Or more importantly, memory access that is somewhat predictable. This makes your CPU caches and memory subsystem more efficient.

If the objects are not allocated in sorted order, and you then sort them, you turn this somewhat predictable memory access into unpredictable random access, which is slower.