Java: What's terrible about unintentional Automatic Packing
Preface: The book tive Java is indeed a classic book, so I am sorry that I didn't buy this book earlier. Let's learn a little bit. Before that, I only knew that integer is the int packing class, and int is the basic type. I never realized that automatic packing has such a big difference."You must prioritize the use of basic types rather than the basic types, and be careful when automatically packing them."
According to the book, I tested the following simple example.
package com.mwq.number;public class Test { public static void main(String[] args) { long time1 = System.currentTimeMillis(); long sum = 0L; for (int i = 0; i < Integer.MAX_VALUE / 2; i++) { sum += i; } System.out.println(sum); long time2 = System.currentTimeMillis(); System.out.println(time2 - time1); Long sum1 = 0L; for (int i = 0; i < Integer.MAX_VALUE / 2; i++) { sum1 += i; } System.out.println(sum); long time3 = System.currentTimeMillis(); System.out.println(time3 - time2); }}
The example is very simple. Let's take a look at the difference between Long and long in + I, and how much time is spent.
View resultsBecause the computation speed from 0 to Integer. MAX_VALUE on my computer is too slow, I only get half of the computation speed.
576460750692810753190357646075069281075310939
The difference is an order of magnitude !!!!!!!!!
When sum is declared as Long rather than long, it will create N (I don't know how many N actually, it's about the 31 power of 2, obviously not mine) multiple Long instances!
Summary: There are a lot of packing and basic types in the project. It seems that it is necessary to optimize it.