Java之创建对象>5.Avoid creating unnecessary objects详解编程语言

String s = new String("stringette"); // DON'T DO THIS!

The improved version is simply the following:

String s = "stringette";

根据生日来判断是否是婴儿潮时期出生的,isBabyBoomer()是一个糟糕的设计,每次调用这个方法都会创建Calendar,TimeZone以及2个Date对象实例,当此方法被频繁调用时将会非常地影响性能。

public class Person { 
    private final Date birthDate; 
   
    // DON'T DO THIS! 
    public boolean isBabyBoomer() { 
        // Unnecessary allocation of expensive object 
        Calendar gmtCal = 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(); 
        return birthDate.compareTo(boomStart) >= 0 && 
        birthDate.compareTo(boomEnd) < 0; 
    } 
}

这个是优化后的方法,The improved version of the Person class creates Calendar, TimeZone, and Date instances only once

这些对象都是初始化后不会再被修改

class Person { 
    private final Date birthDate; 
    /** 
    * The starting and ending dates of the baby boom. 
    */ 
    private static final Date BOOM_START; 
    private static final Date 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 boolean isBabyBoomer() { 
        return birthDate.compareTo(BOOM_START) >= 0 && 
        birthDate.compareTo(BOOM_END) < 0; 
    } 
}

autoboxing(自动装箱)也会带来非常大的性能影响

 // Hideously slow program! Can you spot the object creation? 
public static void main(String[] args) { 
    Long sum = 0L; 
    for (long i = 0; i < Integer.MAX_VALUE; i++) { 
        sum += i; 
    } 
    System.out.println(sum); 
}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15969.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论