Java 实例 - 连接字符串

Java 教程 · 2019-02-10 09:41:37

以下实例演示了通过 "+" 操作符和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

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

Tales from Facebook

Tales from Facebook

Daniel Miller / Polity Press / 2011-4-1 / GBP 55.00

Facebook is now used by nearly 500 million people throughout the world, many of whom spend several hours a day on this site. Once the preserve of youth, the largest increase in usage today is amongst ......一起来看看 《Tales from Facebook》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具