首页 > 其他 > 详细

避免创建不必要的对象

时间:2017-11-08 14:03:05      阅读:254      评论:0      收藏:0      [点我收藏+]


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

 

避免创建不必要的对象

原文:http://www.cnblogs.com/mzxl1987/p/7803452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!