Allocation elimination: when the Java keyword “new” doesn’t create an object

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”

The cost of object creation in Java, including garbage collection

NOTE: The research and views presented below are mine and do not necessarily reflect those of my employer.

I sometimes see advice that object creation in Java is slow and should be avoided. The common counter argument is that it’s not slow, and even if it was slow it should be avoided only after causing a proven performance issue. I always liked the counter argument, to put it to the test I did experiments on how much time a modern JVM takes for object creation and subsequent garbage collection.

Continue reading “The cost of object creation in Java, including garbage collection”