java中字符串的拼接使用StringBuffer而不使用String的理由

来源:互联网 发布:php 验证json格式 编辑:程序博客网 时间:2024/04/29 14:09

java中字符串的拼接操作一定要使用StringBuffer而不建议去使用String,看下面的示例

<span style="font-size:18px;">public class TestStringBuffer {private static final long endTime = 0;public static void main(String[] args) {testSting();testStingBuffer();}public static void testSting(){long startTime = System.currentTimeMillis();String a = "";for (int i = 0; i < 100000; i++) {a  = a +i;}long endTime = System.currentTimeMillis();System.out.println(endTime-startTime);}public static void testStingBuffer(){long startTime = System.currentTimeMillis();StringBuffer a = new StringBuffer();for (int i = 0; i < 100000; i++) {a.append(i);}long endTime = System.currentTimeMillis();System.out.println(endTime-startTime);}}</span>
在两个方法中都循环10000次,并将循环的结果拼接到原有空字符串的末尾,并且分别获取了两段代码的运行时间。

程序的输出结果如下

25302
10

由此可以看出,StringBuffer用作字符串拼接的效率比String高出几个数量级。因此建议使用StringBuffer


1 0
原创粉丝点击