创建str对象的时间是: 6426纳秒,创建str1的时间是:29334纳秒。
采用new String()方式比直接赋值,效率上比第一个慢5~10倍(视机器配置)。从而验证了上面的结论。
字符串连接效率比较
/** * 验证 + 和 StringBuffer还有StringBuilder的效率 */ int count = 50; String s = "t"; long begin = System.nanoTime(); for (int i = 0; i < count; i++) { s += "t"+i; } long end = System.nanoTime(); System.out.println(end - begin); StringBuffer sb = new StringBuffer(); begin = System.nanoTime(); for (int i = 0; i < count; i++) { sb.append("t"+i); } end = System.nanoTime(); System.out.println(end - begin); StringBuilder sbuild = new StringBuilder(); begin = System.nanoTime(); for (int i = 0; i < count; i++) { sbuild.append("t"+i); } end = System.nanoTime(); System.out.println(end - begin); /* Output: 233828 131022 120686
|
可以看到当每次连接的字符串不一样的时候,StringBuilder的效率最高,而+操作的效率最低,
如果每次连接的字符串相同的话,也是+操作最耗时。
/** * 验证 + 和 StringBuffer还有StringBuilder的效率 */ int count = 20; String s = "test"; long begin = System.nanoTime(); for (int i = 0; i < count; i++) { s += "test"; } long end = System.nanoTime(); System.out.println(end - begin); StringBuffer sb = new StringBuffer(); begin = System.nanoTime(); for (int i = 0; i < count; i++) { sb.append("test"); } end = System.nanoTime(); System.out.println(end - begin); StringBuilder sbuild = new StringBuilder(); begin = System.nanoTime(); for (int i = 0; i < count; i++) { sbuild.append("test"); } end = System.nanoTime(); System.out.println(end - begin);
/* Output: 116495 20394 19276
|
上一页 [1] [2] [3]

【责编:Ken】