Which of these two methods for calculating the sum of the first N integers do you think runs the fastest? The answer may surprise you.
Method 1:
public Long sumPrimitive() { long total = 0; for (int i = 0; i < LOOP_SIZE; i++) { total += i; } return total; }
Method 2:
public Long sumMutableWrapper() { long total = 0; for (int i = 0; i < LOOP_SIZE; i++) { MutableWrapper mutableWrapper = new MutableWrapper(total); mutableWrapper.add(i); total = mutableWrapper.value; } return total; } private static class MutableWrapper { private long value; public MutableWrapper(long value) { this.value = value; } public void add(long other) { value += other; } }
Continue reading “Allocation elimination: when the Java keyword “new” doesn’t create an object”