首页 > 代码库 > Java之创建对象>5.Avoid creating unnecessary objects
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); }
Java之创建对象>5.Avoid creating unnecessary objects
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。