避免创建不必要的对象

Posted 点墨小僧

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了避免创建不必要的对象相关的知识,希望对你有一定的参考价值。


import java.util.Calendar;
import java.util.Date;

public class Person {

  private final Date birthDate = new Date();

  //重复创建对象
  public boolean slow () {
    Calendar cal = Calendar.getInstance();
    cal.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
    Date start = cal.getTime();
    
    cal.set(2017, Calendar.JANUARY, 1, 0, 0, 0);
    Date end = cal.getTime();

    return birthDate.compareTo(start) >= 0
    && birthDate.compareTo(end) < 0;
  }

  //改进后
  private static final Date START;
  private static final Date END;

  static {
    Calendar cal = Calendar.getInstance();
    cal.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
    START = cal.getTime();
    
    cal.set(2017, Calendar.JANUARY, 1, 0, 0, 0);
    END = cal.getTime();
  }

  public boolean faster () {
    return birthDate.compareTo(START) >= 0
    && birthDate.compareTo(END) < 0;
  }


  public static void main(String[] args) {
    // TODO Auto-generated method stub

    //较好
    Date start = new Date();
    Person person = new Person();
    for(int i = 0,max = 1000000; i < max; i++) {
      person.faster();
    }
    Date end = new Date();
    
    System.out.println("用时: " + (end.getTime() - start.getTime()));

    //较差
    start = new Date();
    for(int i = 0,max = 1000000; i < max; i++) {
      person.slow();
    }
    end = new Date();
    
    System.out.println("用时: " + (end.getTime() - start.getTime()));

    //较差
    start = new Date();
    String sum = "";
    for(int i = 0,max = 100000; i < max; i++) {
      sum += " ";
    }
    end = new Date();

    System.out.println("用时: " + (end.getTime() - start.getTime()));

    //较好
    start = new Date();
    StringBuilder sb = new StringBuilder();
    for(int i = 0,max = 100000; i < max; i++) {
      sb.append(" ");
    }
    end = new Date();

    System.out.println("用时: " + (end.getTime() - start.getTime()));

  }

}

 

输出结果 : 

用时: 5
用时: 683
用时: 4301
用时: 3

 

以上是关于避免创建不必要的对象的主要内容,如果未能解决你的问题,请参考以下文章

避免创建不必要的对象

effectiveJava避免创建不必要的对象

避免创建不必要的对象

1避免创建不必要的对象

第5条:避免创建不必要的对象

避免创建不必要的对象