关闭

第五条-消除过期的对象引用

204人阅读 评论(0) 收藏 举报

 

package EffectiveJava;

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

public class _2_4 {
	private final Date birthday;
	private static final Date start;
	private static final Date end;
	private  transient Date s = null;
	private transient  Date e = null;
	public _2_4(Date birthday) {
		this.birthday = birthday;
	}
	static {  // 将这个方法写在静态区域块中,这样只需生成一个对象实例,大大提高了效率,但附加的对象貌似太臃肿,如果方法一次都不调用的话,这里初始值就是浪费了
		Calendar cale = Calendar.getInstance();
		cale.set(1946, Calendar.JANUARY, 1, 0, 0);
		start = cale.getTime();
		cale.set(1965,Calendar.JANUARY,1,0,0);
		end = cale.getTime();
	}
	public boolean isBaby() { // 些方法每次被调用的时候都会生成一个Calendar 对象,而执行完方法后又迅速被垃圾收集机制回收,所以效率很慢
		Calendar cale = Calendar.getInstance(); 
		cale.set(1946, Calendar.JANUARY, 1, 0, 0);
		Date start = cale.getTime();
		cale.set(1965,Calendar.JANUARY,1,0,0);
		Date end = cale.getTime();
		return birthday.compareTo(start)>0&&birthday.compareTo(end)<0;
	}
	public boolean bisBaby() { // 这是第三个方法,仿照的 hashmap 中的 keyset,定义两个临时变量 ,如果变量为空,则初始化,如果不为空,则不要初始化
		return this.birthday.compareTo(start)>0&&birthday.compareTo(end)<0;
	}
	public boolean cisBaby() {
		if(s==null || e ==null)
		{
			Calendar cale = Calendar.getInstance();
			cale.set(1946, Calendar.JANUARY, 1, 0, 0);
			this.s = cale.getTime();
			cale.set(1965,Calendar.JANUARY,1,0,0);
			this.e = cale.getTime();
		}
		return s.compareTo(birthday)>0&&e.compareTo(birthday)<0;
	}
	public static void main(String args[]) {
		
		_2_4 person = new _2_4(Calendar.getInstance().getTime());
		long begin = System.currentTimeMillis();
		for(int i=0;i<1000000;i++) {
			person.bisBaby();
		//	person.isBaby();
			person.cisBaby();
		}
		long end = System.currentTimeMillis();
		System.out.println(((double)end-begin)/1000+" s");//3.359 s  0.016 s
			
	}
	
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    多向别人学习