Java 实例 - 连接字符串

3198 1
LZH实名认证 2022-3-19 12:18:39 | 显示全部楼层 |阅读模式
以下实例演示了通过 "+" 操作符和StringBuffer.append() 方法来连接字符串,并比较其性能:

StringConcatenate.java 文件
public class StringConcatenate {
    public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            String result = "This is"
            + "testing the"
            + "difference"+ "between"
            + "String"+ "and"+ "StringBuffer";
        }
        long endTime = System.currentTimeMillis();
        System.out.println("字符串连接"
        + " - 使用 + 操作符 : "
        + (endTime - startTime)+ " ms");
        long startTime1 = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            StringBuffer result = new StringBuffer();
            result.append("This is");
            result.append("testing the");
            result.append("difference");
            result.append("between");
            result.append("String");
            result.append("and");
            result.append("StringBuffer");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("字符串连接"
        + " - 使用 StringBuffer : "
        + (endTime1 - startTime1)+ " ms");
    }
}
以上代码实例输出结果为:

字符串连接 - 使用 + 操作符 : 0 ms
字符串连接 - 使用 StringBuffer : 6 ms
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行