Reputation: 55
I was reading the source code of DualPivotQuicksort Algorithm in java these days. I find an interesting comment in code. It says:
/*
* Here and below we use "a[i] = b; i++;" instead
* of "a[i++] = b;" due to performance issue.
*/
a[less] = ak;
++less;
I just don't know why. Can anybody help me?
Upvotes: 1
Views: 363
Reputation:
I decided to compare the execution times for 2^26 operations for each option. I iterated this 4096 times and got and average for each option.
import java.util.ArrayList;
public class TestClass
{
public static void main (String[] args)
{
long startTime, endTime;
final int twoToPower26 = 67108864;
int[] a1 = new int[twoToPower26];
int[] a2 = new int[twoToPower26];
int i = 0;
int b = 1;
ArrayList<Long> optionATimes = new ArrayList<Long>();
ArrayList<Long> optionBTimes = new ArrayList<Long>();
for (int k = 0; k < 4096; k++)
{
i = 0;
//OPTION A: "a[i] = b; i++;"
startTime = System.currentTimeMillis();
while (i < twoToPower26)
{
a1[i] = b;
i++;
}
endTime = System.currentTimeMillis();
optionATimes.add(endTime - startTime);
i = 0;
//OPTION B: "a[i++] = b;"
startTime = System.currentTimeMillis();
while (i < twoToPower26)
{
a2[i++] = b;
}
endTime = System.currentTimeMillis();
optionBTimes.add(endTime - startTime);
System.out.println(k);
}
double averageTimeOptionA = calculateAverage(optionATimes);
double averageTimeOptionB = calculateAverage(optionBTimes);
System.out.println("OPTION A average time for 2^26 operations: " + averageTimeOptionA);
System.out.println("OPTION B average time for 2^26 operations: " + averageTimeOptionB);
}
public static double calculateAverage(ArrayList<Long> times) {
Long sum = (long) 0;
for (Long time : times) {
sum += time;
}
return sum.doubleValue() / times.size();
}
}
The results:
OPTION A average time for 2^26 operations: 105.9140625 ms
OPTION B average time for 2^26 operations: 105.846923828125 ms
The difference in average time for each option is only about 67 nano seconds over 2^26 iterations and in this case OPTION B was slightly faster.
I feel this shows with almost certainty that there is no difference in performance. Most likely the compiler interprets each option in the same.
Upvotes: 5