Below are two versions of code calculating the number of triples in an array adding up to zero. One uses a function call to make the actual test, and the other performs the test in the body of the function.
It exhibits an interesting behaviour in terms of performance time. The variant using function call performs two times faster. Why?
/**
* Find triples of integers, which add up to zero
*/
public class SumCheck {
public static void main(String[] args) {
int a = 1000000;
int b = 3000;
int[] input = new int[b];
for (int i = 0; i < b; i++) {
input[i] = StdRandom.uniform(-a, a);
}
double startTime2 = System.currentTimeMillis() / 1000.0;
int counter2 = count2(input);
double endTime2 = System.currentTimeMillis() / 1000.0;
System.out.printf("%d +(%.0f seconds)\n", counter2, endTime2 - startTime2);
double startTime = System.currentTimeMillis() / 1000.0;
int counter = count(input);
double endTime = System.currentTimeMillis() / 1000.0;
System.out.printf("%d +(%.0f seconds)\n", counter, endTime - startTime);
}
private static int count(int[] a) {
int counter = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
for (int k = j + 1; k < a.length; k++) {
if (a[i] + a[j] + a[k] == 0)
counter++;
}
}
}
return counter;
}
// same as count function but comparison is being done through a function call
private static int count2(int[] a) {
int counter = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
for (int k = j + 1; k < a.length; k++) {
counter = counter + check(a, i, j, k);
}
}
}
return counter;
}
private static int check(int[] a, int i, int j, int k) {
if (a[i] + a[j] + a[k] == 0) {
return 1;
}
return 0;
}
}
In particular, one of the runs yields the following times: 12 seconds, 33 seconds.