Background:
When you extract methods out of long code pieces, you often run into the call-by-value problem with primitive variables. You cannot change those primitive parameters in the extracted method so that the caller sees the changes. You can avoid that by making the primitive variable an array with only one element. Then it is effectively used call-by-reference. However it is now an object on the heap. Is the escape analysis of Java clever enough to understand that and use the stack despite that?
Given following code and the case it could not be inlined:
public class EscapeAnalysisTest {
public static void main(String[] args) {
final Set<Integer> integers = new HashSet<>();
integers.add(1);
integers.add(9);
integers.add(8);
integers.add(4);
// and so on ...
final long[] product = new long[1];
final long[] sum = new long[1];
final long[] count = new long[1];
final int[] max = new int[1];
final int[] min = new int[1];
product[0] = 1L;
max[0] = Integer.MIN_VALUE;
min[0] = Integer.MAX_VALUE;
for (Integer i : integers) {
calcSomeValues(product, sum, count, max, min, i);
}
System.out.println("Product :" + product[0]);
System.out.println("Sum :" + sum[0]);
System.out.println("Count:" + count[0]);
System.out.println("Max:" + max[0]);
System.out.println("Min:" + min[0]);
}
private static void calcSomeValues(final long[] product, final long[] sum, final long[] count, final int[] max,
final int[] min, Integer i) {
product[0] *= i;
sum[0] += i;
count[0]++;
max[0] = Math.max(max[0], i);
min[0] = Math.min(min[0], i);
}
}