码迷,mamicode.com
首页 > 编程语言 > 详细

Java之创建对象>5.Avoid creating unnecessary objects

时间:2017-05-27 19:02:48      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:java   i++   static   blog   创建   instance   end   创建ca   object c   

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);
}

 

Java之创建对象>5.Avoid creating unnecessary objects

标签:java   i++   static   blog   创建   instance   end   创建ca   object c   

原文地址:http://www.cnblogs.com/frankyou/p/6913941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!