标签:
场景一:
public class Test { public static void main(String[] args) { //参数"terrible"会创建一个对象 //然后,new String(),这个语句会创建一个对象 //所以,这个语句执行过程中,会创建两个对象 String s = new String("terrible."); //只创建一个对象,该对象的引用被赋值到变量 ok String ok = "This is ok" ; } }
import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class Person { private final Date birthDate ; public Person(Date birthDate) { // Defensive copy - see Item 39 this. birthDate = new Date(birthDate.getTime()); } // Other fields, methods omitted // 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; } }
所以,对于这种情况,可以将这些创建的对象定义为一个静态的类实例。修改为:
import java.util.Calendar; import java.util.Date; import java.util.TimeZone; class Person { private final Date birthDate ; public Person(Date birthDate) { // Defensive copy - see Item 39 this. birthDate = new Date(birthDate.getTime()); } // Other fields, methods /** * 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; } }
//一段运行缓慢的代码 public class Sum { // 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编译器,根据装箱技术,会将上述代码转换为:
for ( long j = 0; j < Integer. MAX_VALUE; j++) { sum += Long. valueOf(j); } System. out.println(sum);
这样会创建Integer.MAX_VALUE个Long个包装类的实例,从而影响了性能。
正确的代码是:
long sum = 0L; for ( long i = 0; i < Integer. MAX_VALUE; i++) { sum += i; } System. out.println(sum);
这样就可以避免创建Integer.MAX_VALUE个Long包装类实例了。
标签:
原文地址:http://www.cnblogs.com/ttylinux/p/4356418.html