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

Purpose

During the review, I came across a code that is a mixture of Integer and int. For a moment I thought that there would be no problem because it would be converted by auto boxing, but I was wondering what the performance was, so I would like to verify it.

Verification environment

Source code for verification

** 1. Pattern with a mixture of 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 + "millisecond");

** 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 + "millisecond");

Implementation procedure

--Perform 1,000,000 addition processing using the verification source code. The average time is calculated by measuring each three times. Round to the first decimal place.

Implementation results

** 1. Pattern with a mixture of reference types and primitive types **

--First time: 15 ms --Second time: 16 ms --Third time: 15 ms --Average: 15.33 ms

** 2. Primitive type only pattern **

--First time: 5 ms --Second time: 4 ms --Third time: 4 ms --Average: 4.33 ms

Consideration

The mixed reference and primitive patterns averaged 15.33 ms, while the primitive-only patterns averaged 4.33 ms. It can be seen that it takes about four times as long when autoboxing is working with a mixture of reference types and primitive types. It turns out that if dust accumulates, it will be a mountain, and depending on the number of data, it should not be meaninglessly auto-boxing.

See you again (^_^) Noshi

Recommended Posts

[Java] Code that is hard to notice but terribly slow
[Java] Map # merge is hard to understand.
Write code that is difficult to test
Code that is difficult to debug and parse
Write code that is easy to maintain (Part 1)
Write code that is easy to maintain (Part 4)
Write code that is easy to maintain (Part 3)
[Windows] Java code is garbled
Java 14 new features that could be used to write code
Let's write a code that is easy to maintain (Part 2) Name
"Let's write versatile code that is easy to use over time" (nth time)
To you who lament that the conversion of JODConverter + LibreOffice is slow
Think of test code that is easy to understand through Comparator testing
[Introduction to Java] I tried to summarize the knowledge that I think is essential
[Java: memorandum] Until the line feed code CRLF is changed to LF
Java Realm is difficult to handle 3 points
[Java] Flow from source code to execution
Java String class methods that are a little useful to know but don't know
Initialize Ruby array with 0 like Java, that is, set the default value to 0