effictive--避免创建不必要的对象

demo01:

package com.xiaohao.effective;

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

/**
 * 避免创建不必要的对象Calendar,BOOM_START,BOOM_END
 * @author Administrator
 *
 */
public class Demo01 {
	private static final Date BOOM_START;
	private static final Date BOOM_END;
	
	static {
		Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		gmtCal.set(1946,Calendar.JANUARY,1,0,0,0);
		BOOM_START = gmtCal.getTime();
		gmtCal.set(1965,Calendar.JANUARY,1,0,0,0);
		BOOM_END = gmtCal.getTime();
	}
	
	public static boolean isBabyBoomer(Date birthDate) {
		return birthDate.compareTo(BOOM_START) >= 0 &&
				birthDate.compareTo(BOOM_END) < 0;
	}
}


demo02:

package com.xiaohao.effective;

import java.util.Date;
/**
 * countNum01方法中每执行一次sum +=1,实际上是sum = sum + 1,但是sum是对象,对象不支持“+”运算,所以sum
 * 会进行自动拆箱和装箱,sum = sum.intValue() + 1; Long sum = new Long(sum);
 * 就会创建一个Long类型对象,非常耗性能 , 而countNum02并不会如此。
 * 注意:要优先使用基本类型而不是装箱基本类型,要当心无意识的自动装箱
 * @author Administrator
 *
 */
public class Demo02 {
	private static Demo02 d= new Demo02();
	
	public static void countNum01(){
		Long sum = 0L;
		long t1 = new Date().getTime();
		for(long i=0;i

测试demo02:

package com.xiaohao.test;

import org.junit.Test;

import com.xiaohao.effective.Demo02;

public class TestEffective {
	
	@Test
	public void testDemo02() {
		Demo02.getInstance().countNum01();
		
		Demo02.getInstance().countNum02();
	}
}

output:

2305843005992468481 :case 7277
2305843005992468481 :case 655

你可能感兴趣的:(Effictive)