避免创建不必要的对象


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

 

转载于:https://www.cnblogs.com/mzxl1987/p/7803452.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值