[Java] [Java] Code that is hard to notice but is terribly slow

1 minute read

Purpose

I was doing a review and came across a code that was a mixture of Integer and int. I thought for a second that auto-boxing would cause a problem, but I was wondering what the performance was, so I would like to verify it.

Verification environment

  • Eclipse Oxygen.3a Release (4.7.3a)
  • Java8

Source code for verification

1. Pattern that mixes reference types and primitive types

qiita.java


long begin = 0L;
long end = 0L;

begin = System.currentTimeMillis();

Integer sum = 0;

for(int i = 0; i <1000000; i++) {
sum += i;
}

end = System.currentTimeMillis();

System.out.println(end-begin + "ms");

2. Primitive type only pattern

qiita.java


long begin = 0L;
long end = 0L;

begin = System.currentTimeMillis();

int sum = 0;

for(int i = 0; i <1000000; i++) {
sum += i;
}

end = System.currentTimeMillis();

System.out.println(end-begin + "ms");

Implementation procedure

  • Add 1,000,000 times using the verification source code. The average time is calculated by measuring each three times. Round to the second decimal place.

Implementation result

1. Pattern that mixes reference types and primitive types

  • 1st time: 15 ms
  • Second time: 16 ms
  • 3rd time: 15 ms
  • Average: 15.33 ms

2. Primitive type only pattern

  • 1st time: 5 ms
  • Second time: 4 ms
  • 3rd time: 4 ms
  • Average: 4.33 ms

Consideration

Patterns with mixed reference types and primitive types averaged 15.33 ms, while patterns with only primitive types averaged 4.33 ms. It can be seen that it takes about 4 times as long as the auto-boxing is working when the reference type and the primitive type are mixed. It turned out to be a pile of dust, and depending on the number of data records, it should be pointless to avoid autoboxing.

See you again (^_^)