论坛首页 Java企业应用论坛

if-else会比switch-case更快吗?

浏览 3764 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-10-24   最后修改:2012-10-24
public class CaseMapCompare {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<Integer, Object> storage = new HashMap<Integer, Object>();
		storage.put(1, 1);
		storage.put(2, 2);
		storage.put(3, 3);
		storage.put(4, 3);
		storage.put(5, 3);
		storage.put(6, 3);
		storage.put(7, 3);
		storage.put(8, 3);
		storage.put(9, 3);
		storage.put(0, -1);

		int count = 1000000000;
		int len = 9;
		long start = System.nanoTime();
		for(int i=0; i<count; i++) {
			storage.get(i%len);
		}
		long end = System.nanoTime();
		System.out.println("xmap use time: "+timeCal(end - start));
		//---
		start = System.nanoTime();
		for(int i=0; i<count; i++) {
			caseFunc(i%len);
		}
		end = System.nanoTime();
		System.out.println("case use time: "+timeCal(end - start));
		//---
		start = System.nanoTime();
		for(int i=0; i<count; i++) {
			ifFunc(i%len);
		}
		end = System.nanoTime();
		System.out.println("xxif use time: "+timeCal(end - start));
	}
	
	public static int caseFunc(int type) {
		switch(type) {
		case 1:
			return 1;
		case 2:
			return 2;
		case 3:
			return 3;
		case 4:
			return 3;
		case 5:
			return 3;
		case 6:
			return 3;
		case 7:
			return 3;
		case 8:
			return 3;
		case 9:
			return 3;
		default:
			return -1;
		}
	}
	
	
	public static int ifFunc(int type) {
		if(type == 1)
			return 1;
		else if(type == 2)
			return 2;
		else if(type == 3)
			return 3;
		else if(type == 4)
			return 3;
		else if(type == 5)
			return 3;
		else if(type == 6)
			return 3;
		else if(type == 7)
			return 3;
		else if(type == 8)
			return 3;
		else if(type == 9)
			return 3;
		else
			return -1;
	}
	
	private static String timeCal(long time) {
		double dtime = (double)time /(1000D * 1000D);
		return dtime + "ms";
	}

}

 

测试结果:

xmap use time: 44961.207ms
case use time: 25089.44364ms
xxif use time: 25076.96492ms
 
   发表时间:2012-10-24  
分支不够多,MAP的优势体现不出来
0 请登录后投票
   发表时间:2012-10-26  
量太少了吧
0 请登录后投票
   发表时间:2013-05-06  
长跑的快,和短跑的快,完全是不同的概念呀,楼主。你想证明什么呢。
0 请登录后投票
   发表时间:2013-05-07  
switch最快才合道理啊
0 请登录后投票
   发表时间:2013-05-07  
老是研究这种有嘛意思。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics