当前位置:首页 > 开发 > 编程语言 > Java > 正文

java 字符串拼接效率对比

发表于: 2012-10-09   作者:晨必须的   来源:转载   浏览:
摘要:   package demo; import java.util.ArrayList; import java.util.List; import org.junit.Test; /**  * @className:Test203.java  * @classDescription: 测试字符串拼接效率  * @author:qiuchen&

 

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<String> list = new ArrayList<String>(); 

        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

 

java 字符串拼接效率对比

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号