java 字符串拼接方法性能大比拼

由于在实际项目中经常会打log,这 就要用到字符串拼接, 本文测试了JAVA中的四种字符串拼接方法的性能。

1.使用“+”拼接字符串

	public static String f1(String p1, String p2, String p3){
		return "["+p1+"]["+p2+"]["+p3+"]";
	}

 2.使用StringBuilder拼接字符串

	public static String f2(String p1, String p2, String p3){
		StringBuilder sb = new StringBuilder();
		sb.append("[").append(p1).append("]");
		sb.append("[").append(p2).append("]");
		sb.append("[").append(p3).append("]");
		return sb.toString();
	}

 3.使用String.format拼接字符串

	public static String f3(String p1, String p2, String p3){
		return String.format("[%s][%s][%s]", p1, p2, p3);
	}

 4.使用MessageFormat.format拼接字符串

	public static String f4(String p1, String p2, String p3){
		return MessageFormat.format("[{0}][{1}][{2}]", p1, p2, p3);
	}

 测试:

	public static void main(String[] args) {
		int count = 100000;
		String bigStr = "2015-11-23 18:51:15,661 [nioEventLoopGroup-2-1] ERROR test_t1 [] - [test_t1][ChannelHandler_exceptionCaught]远程主机强迫关闭了一个现有的连接。";
		
		long start = System.currentTimeMillis();
		for(int i=0; i<count;i ++){
			f1("11111", "222222", bigStr);
		}
		long end = System.currentTimeMillis();
		System.err.println("f1 : " + (end - start));
		start = System.currentTimeMillis();
		for(int i=0; i<count;i ++){
			f2("11111", "222222", bigStr);
		}
		end = System.currentTimeMillis();
		System.err.println("f2 : " + (end - start));
		start = System.currentTimeMillis();
		for(int i=0; i<count;i ++){
			f3("11111", "222222", bigStr);
		}
		end = System.currentTimeMillis();
		System.err.println("f3 : " + (end - start));
		start = System.currentTimeMillis();
		for(int i=0; i<count;i ++){
			f4("11111", "222222", bigStr);
		}
		end = System.currentTimeMillis();
		System.err.println("f4 : " + (end - start));
	}

 测试结果:(单位毫秒)

f1 : 18

f2 : 40

f3 : 386

f4 : 134

结论:使用“+”拼接字符串性能最好,使用String.format性能最差,所以还是老老实实用“+”来拼字符串吧,虽然难看点

猜你喜欢

转载自yuancihang.iteye.com/blog/2258763