1. 程式人生 > >effictive--避免建立不必要的物件

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<Integer.MAX_VALUE;i++) {
			sum += i;
		}
		long t2 = new Date().getTime();
		System.out.println(sum + " :case " + (t2-t1));
	}
	
	public static void countNum02(){
		long sum = 0L;
		long t1 = new Date().getTime();
		for(long i=0;i<Integer.MAX_VALUE;i++) {
			sum += i;
		}
		long t2 = new Date().getTime();
		System.out.println(sum + " :case " + (t2-t1));
	}
	
	public static Demo02 getInstance() {
		if(d == null) {
			d = new Demo02();
		}
		return d;
	}
}

測試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