Java: What's terrible about unintentional Automatic Packing

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.