码迷,mamicode.com
首页 > 其他好文 > 详细

避免创建不必要的对象

时间:2017-11-08 14:51:24      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:uil   创建   cal   .com   instance   private   method   port   sys   


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

 

避免创建不必要的对象

标签:uil   创建   cal   .com   instance   private   method   port   sys   

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

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