本帖最后由 justin1258 于 2014-8-11 13:01 编辑
我写了四种不同的方法来拼接字符串:用+=,+,StringBuffer,StringBuilder。代码如下:
- public class PerformanceTest {
- long times;
- public PerformanceTest(long times) {
- this.times = times;
- }
-
- public PerformanceTest start(String title, PerformanceTest.Perform performance) {
- long start = System.nanoTime();
-
- for (int i = 0; i < times; i++) {
- performance.perform();
- }
-
- System.out.println((System.nanoTime() - start) + "(" + title + ")");
-
- return this;
- }
-
- protected interface Perform{
- public void perform();
- }
- }
复制代码 上面是用来测试的通用类,下面是具体的测试代码:
- public class StringConcatTest {
-
- public static void main(String... args) {
- new PerformanceTest(1000000).start("用+=", new PerformanceTest.Perform() {
- @Override
- public void perform() {
- concat1("aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff");
- }
- }).start("用StringBuffer", new PerformanceTest.Perform() {
- @Override
- public void perform() {
- concat2("aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff");
- }
- }).start("用+", new PerformanceTest.Perform() {
- @Override
- public void perform() {
- concat3("aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff");
- }
- }).start("用StringBuilder", new PerformanceTest.Perform() {
- @Override
- public void perform() {
- concat4("aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff");
- }
- });
- }
-
- static String concat1(String s1, String s2, String s3, String s4, String s5, String s6){
- String result = "";
- result += s1;
- result += s2;
- result += s3;
- result += s4;
- result += s5;
- result += s6;
-
- return result;
- }
-
- static String concat2(String s1, String s2, String s3, String s4, String s5, String s6){
- StringBuffer buffer = new StringBuffer();
- buffer.append(s1).append(s2).append(s3).append(s4).append(s5).append(s6);
-
- return buffer.toString();
- }
-
- static String concat3(String s1, String s2, String s3, String s4, String s5, String s6){
- return s1 + s2 + s3 + s4 + s5 + s6;
- }
-
- static String concat4(String s1, String s2, String s3, String s4, String s5, String s6){
- StringBuilder builder = new StringBuilder();
- builder.append(s1).append(s2).append(s3).append(s4).append(s5).append(s6);
-
- return builder.toString();
- }
- }
复制代码
在我机器上运行1000000次的结果如下:
364650466(用+=)
266889252(用StringBuffer)
9372288(用+)
109691345(用StringBuilder)
下面分析下结果:
用+=和+操作本质就是调用StringBuolder的append方法。
第一种之所以最差是因为每次链接都要重新创建一个字符串
第二种方法虽然用到了StringBuffer,但是我估计是因为线程同步导致效率低
主要是第三和第四种,下面是我截的两种方法的字节码:
第三种:
第四种:
我看着两段代码似乎没有什么太大的不同,为什么效率会差那么多?
|
|