WEB开发网
开发学院软件开发Java Java高效运行必备:如何选择使用String、StringBu... 阅读

Java高效运行必备:如何选择使用String、StringBuffer与StringBuilde

 2009-09-09 00:00:00 来源:WEB开发网   
核心提示: 所以不需要太多的时间了,但大家这里要注意的是,Java高效运行必备:如何选择使用String、StringBuffer与StringBuilde(3),如果你的字符串是来自另外的String对象的话,速度就没那么快了,StringBuilder实际上是我们的首选,只有在多线程时才可以考虑使用St

所以不需要太多的时间了。但大家这里要注意的是,如果你的字符串是来自另外的String对象的话,速度就没那么快了,譬如:

String str2 = “This is only a”;
String str3 = “ simple”;
String str4 = “ test”;
String str1 = str2 +str3 + str4;

这时候JVM会规规矩矩的按照原来的方式去做。

为了测试这三个类的累加不同次数字符串时的效率,我们编写一个测试类,分别按次数累加字符串:

程序11-8  TestString.java

package test.String;

public class TestString {
   
    static int count = 100;//循环次数
   
// 测试String
    public static void testString() {
        long start = System.nanoTime();
        String str = "";
        for (int i = 0; i < count; i++) {
            str += "," + i;
        }
        long end = System.nanoTime();
        System.out.println("String:" + (end - start));
    }
   
    // 测试StringBuffer
    public static void testStringBuffer() {
        long start = System.nanoTime();
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < count; i++) {
            str.append(",").append(i);
        }
        long end = System.nanoTime();
        System.out.println("StringBuffer:" + (end - start));
    }
   
    // 测试StringBuilder
    public static void testStringBuilder() {
        long start = System.nanoTime();
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < count; i++) {
            str.append(",").append(i);
        }
        long end = System.nanoTime();
        System.out.println("StringBuilder:" + (end - start));
    }

    public static void main(String[] args) {
        TestString.testString();
        TestString.testStringBuffer();
        TestString.testStringBuilder();
    }
}

运行该程序执行的测试时间:

表11-2  测试结果

毫微秒 String StringBuffer StringBuilder
1次 69,562 46,934 8,101
10次 109,791 57,269 24,025
100次 431,619 172,089 128,228
1000次 8,274,236 876,368 270,985
1万次 704,425,841 2,673,524 1,388,166
10万次 溢出 20,926,961 11,669,361
100万次 溢出 246,871,041 137,586,760

String在10w次循环时就溢出了,而StringBuffer在100万次循环时间为246ms,StringBuilder的时间为137ms。显然选择优先级为:StringBuilder>StringBuffer>String。因此,对于这三个类的使用,我们需要按照以下情况去选择:

● 如果你偶尔对简单的字符串常量进行拼接,那么可以使用String,它足够简单而且轻量级;

● 如果你需要经常进行字符串的拼接、累加操作,请使用StringBuffer或StringBuilder;

● 如果是在单线程的环境中,建议使用StringBuilder,它要比StringBuffer快;如果是在多线程的环境中,建议使用StringBuffer,它是线程安全的;

因此,StringBuilder实际上是我们的首选,只有在多线程时才可以考虑使用StringBuffer,只有在字符串的拼接足够简单时才使用String。

上一页  1 2 3 

Tags:Java 高效 运行

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接