java 字符串拼接效率对比

阅读更多

 

package demo;

import java.util.ArrayList;

import java.util.List;

import org.junit.Test;

/**

 * @className:Test203.java

 * @classDescription: 测试字符串拼接效率

 * @author:qiuchen 

 * @createTime:2012-10-9

 */

public class Test{

 

public static void main(String[] args) {

 

}

 

@Test

public void testPlus(){

String s = ""; 

        long begin = System.currentTimeMillis(); 

        for (int i = 0; i < 10000; i++) { 

            s = s + String.valueOf(i); 

        } 

        long end = System.currentTimeMillis();

        System.out.println("+:"+(end - begin));

}

 

@Test

public void testConcat(){

String s = ""; 

        long begin = System.currentTimeMillis(); 

        for (int i = 0; i < 10000; i++) { 

            s = s.concat(String.valueOf(i)); 

        }

        long end = System.currentTimeMillis();

        System.out.println("concat:"+(end - begin)); 

}

 

@Test

public void testAppend(){

StringBuffer s = new StringBuffer(); 

        long begin = System.currentTimeMillis(); 

        for (int i = 0; i < 10000; i++) { 

            s.append(String.valueOf(i));

        }

        long end = System.currentTimeMillis();

        System.out.println("StringBuffer append:"+(end - begin)); 

}

 

@Test

public void testBuilder(){

StringBuilder s = new StringBuilder(); 

        long begin = System.currentTimeMillis(); 

        for (int i = 0; i < 10000; i++) { 

            s.append(String.valueOf(i));

        }

        long end = System.currentTimeMillis();

        System.out.println("StringBuilder append:"+(end - begin)); 

}

 

@Test

public void testAdd(){

List list = new ArrayList(); 

        long begin = System.currentTimeMillis(); 

        for (int i = 0; i < 10000; i++) { 

            list.add(String.valueOf(i));

        }

        long end = System.currentTimeMillis();

        System.out.println("List add:"+(end - begin));

}

 

}

 

+:687

concat:329

StringBuffer append:0

StringBuilder append:0

List add:15

 

 

+:656

concat:344

StringBuffer append:0

StringBuilder append:0

List add:0

 

+:656

concat:313

StringBuffer append:16

StringBuilder append:0

List add:0

 

+:672

concat:328

StringBuffer append:0

StringBuilder append:16

List add:0

 

你可能感兴趣的:(String,StringBuffer,append,concat,add)