Java: The scary thing about auto-boxing in the unconscious

Source: Internet
Author: User

Preface : "Effective Java" is really a classic book, it is really not a little early to buy this book and feel sorry. Again to learn a little knowledge, before, I just know that integer is the boxed class of int, and int is the basic type, never realize that there is such a big difference in automatic boxing, " to take precedence over the basic type, instead of boxing the basic type, beware of the unconscious automatic boxing." "

As written in the book, I tested the following simple examples.

 PackageCom.mwq.number; Public  class Test {     Public Static void Main(string[] args) {Longtime1 = System.currenttimemillis ();Longsum =0L for(inti =0; I < Integer.max_value/2;        i++) {sum + = i; } System.out.println (sum);LongTime2 = System.currenttimemillis ();        System.out.println (TIME2-TIME1); Long sum1 =0L for(inti =0; I < Integer.max_value/2;        i++) {sum1 + = i; } System.out.println (sum);LongTime3 = System.currenttimemillis ();    System.out.println (time3-time2); }}

The example is simple enough to see how long and long are different in +i, and how much time is spent.

See the result , because my computer calculates 0 to integer.max_value the operation speed is too slow, therefore only takes half of the quantity.

576460750692810753190357646075069281075310939

An order of magnitude difference!!!!!!!!!

Sum is declared as a long instead of a long, it will create n (how many n, I really do not know, the book is said to be 2 of the 31 square, obviously I am not) multiple long instances!

Summary : The project has a large number of boxing and basic types, it seems to be a good optimization.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java: The scary thing about auto-boxing in the unconscious

Related Article

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.