Java creation object >5.avoid creating unnecessary objects

Source: Internet
Author: User

New  //DON ' T do this!

The improved version is simply the following:

String s = "Stringette";

According to the birthday to determine whether it was born in the baby Boomers, Isbabyboomer () is a bad design, each call to this method will create a Calendar,timezone and 2 Date object instances, when this method is frequently called will greatly affect performance.

 Public classPerson {Private FinalDate birthDate;     //DON ' T do this!     Public BooleanIsbabyboomer () {//unnecessary allocation of expensive object        CalendarGmtcal =calendar.getinstance (Timezone.gettimezone ("GMT")); Gmtcal.set (1946, Calendar.january, 1, 0, 0, 0); Date Boomstart=Gmtcal.gettime (); Gmtcal.set (1965, Calendar.january, 1, 0, 0, 0); Date boomend=Gmtcal.gettime (); returnBirthdate.compareto (Boomstart) >= 0 &&Birthdate.compareto (boomend)< 0; }}

This is the optimized method, the improved version of the person class creates Calendar, TimeZone, and Date instances only once

These objects are not modified after initialization

classPerson {Private FinalDate birthDate;    /*** The starting and ending dates of the baby boom. */    Private Static FinalDate Boom_start; Private Static FinalDate Boom_end; Static{Calendar gmtcal=calendar.getinstance (Timezone.gettimezone ("GMT")); Gmtcal.set (1946, Calendar.january, 1, 0, 0, 0); Boom_start=Gmtcal.gettime (); Gmtcal.set (1965, Calendar.january, 1, 0, 0, 0); Boom_end=Gmtcal.gettime (); }     Public BooleanIsbabyboomer () {returnBirthdate.compareto (Boom_start) >= 0 &&Birthdate.compareto (boom_end)< 0; }}

Autoboxing (Automatic boxing) also has a very large performance impact

// hideously Slow program! Can you spot the object creation?  Public Static void Main (string[] args) {    = 0L;      for (long i = 0; i < Integer.max_value; i++) {        + =   i ;    }    SYSTEM.OUT.PRINTLN (sum);}

Java creation object >5.avoid creating unnecessary objects

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.