今天看到本组模块的中看到了下面这样的代码,其实我蛮好奇的,为什么要使用MessageFormat这么生涩的写法,直接使用String plus不是更简单,更明了么?
MessageFormat.format("{0} {1}",DateUtil.getDate(DateUtil.YEAR_MONTH_DAY_PATTERN),ResourceUtil.getString("attendance.common.week"+week))
小生心机一动,不然Google下看有与我有同样想法的骚年,以关键字java messageformat vs string plus,果然不少,好了不吹牛逼了,直接上代码!
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
}
end = System.currentTimeMillis();
System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder bldString = new StringBuilder("Hi ");
bldString.append(i).append("; Hi to you ").append(i * 2).toString();
}
end = System.currentTimeMillis();
System.out.println("StringBuilder = " + ((end - start)) + " millisecond");
}
执行结果:
Concatenation = 151 millisecond
Format = 2289 millisecond
MessageFormat = 442 millisecond
StringBuilder = 136 millisecond
从数据中我们可以得到结论:
- String plus并没有想象中性能那么差,可能与JVM对String优化有关(不了解,仅仅是瞎猜);
- MessageFormat性能没有想象中的好,如果自己调试的话,MessageFormat会先将对象转换为String,然后再做format操作;
参考链接: