JAVA的字符串拼接与性能

发表于:2013-6-26 09:25

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:陈皓 译    来源:51Testing软件测试网采编

  概述:本文主要研究的是JAVA的字符串拼接的性能,原文中的测试代码在功能上并不等价,导致concat的测试意义不大。不过原作者在评论栏给了新的concat结果,如果有兴趣的同学建议自己修改代码测试。

  原文出处:http://www.venishjoe.net/2009/11/java-string-concatenation-and.html

  在JAVA中拼接两个字符串的最简便的方式就是使用操作符”+”了。如果你用”+”来连接固定长度的字符串,可能性能上会稍受影响,但是如果你是在 循环中来”+”多个串的话,性能将指数倍的下降。假设有一个字符串,我们将对这个字符串做大量循环拼接操作,使用”+”的话将得到最低的性能。但是究竟这 个性能有多差?如果我们同时也把StringBuffer,StringBuilder或String.concat()放入性能测试中,结果又会如何 呢?本文将会就这些问题给出一个答案!

  我们将使用Per4j来计算性能,因为这个工具可以给我们一个完整的性能指标集合,比如最小,最大耗时,统计时间段的标准偏差等。在测试代码中,为了得到一个准确的标准偏差值,我们将执行20个拼接”*”50,000次的测试。下面是我们将使用到的拼接字符串的方法:

  ● Concatenation Operator (+)

  ● String concat method – concat(String str)

  ● StringBuffer append method – append(String str)

  ● StringBuilder append method – append(String str)

  最后,我们将看看字节码,来研究这些方法到底是如何执行的。现在,让我们先开始来创建我扪的类。注意为了计算每个循环的性能,代码中的每段测试代码都需要用Per4J库进行封装。首先我们先定义迭代次数

private static  final int  OUTER_ITERATION=20;
private static final int INNER_ITERATION=50000;

  接下来,我们将使用上述4个方法来实现我们的测试代码。

String addTestStr ="";
String concatTestStr ="";
StringBuffer concatTestSb =null;
StringBuilder concatTestSbu =null;
   
for(intouterIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {
    StopWatch stopWatch =newLoggingStopWatch("StringAddConcat");
    addTestStr ="";
    for(intinnerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++)
    addTestStr +="*";
    stopWatch.stop();
}       
   
for(intouterIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {
    StopWatch stopWatch =newLoggingStopWatch("StringConcat");
    concatTestStr ="";
    for(intinnerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++)
    concatTestStr.concat("*");
    stopWatch.stop();
}
   
for(intouterIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {
    StopWatch stopWatch =newLoggingStopWatch("StringBufferConcat");
    concatTestSb =newStringBuffer();
    for(intinnerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++)
    concatTestSb.append("*");
    stopWatch.stop();
}
   
for(intouterIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {
    StopWatch stopWatch =newLoggingStopWatch("StringBuilderConcat");
    concatTestSbu =newStringBuilder();
    for(intinnerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++)
    concatTestSbu.append("*");
    stopWatch.stop();
}

  接下来通过运行程序来生成性能指标。我的运行环境是64位的Windown7操作系统,32位的JVM(7-ea) 带4GB内存,双核Quad 2.00GHz的CPU的机器。

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号