zoukankan      html  css  js  c++  java
  • java字符串拼接与性能

    使用

    • Concatenation Operator (+)
    • String concat method – concat(String str)
    • StringBuffer append method – append(String str)
    • StringBuilder append method – append(String str)

    进行性能测试。

    环境 win7 32位, cpu双核2.5GHZ,2G内存。

    测试代码如下:

        private final static int OUTER_ITERATION = 10;
        private final static int INNER_ITERATION = 50000;
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            String addTestStr = "";
            String concatTestStr = "";
            StringBuffer concatTestSb = null;
            StringBuilder concatTestSbu = null;
    
            for (int outerIndex = 0; outerIndex < OUTER_ITERATION; outerIndex++) {
                StopWatch stopWatch = new LoggingStopWatch("StringAddConcat");
                addTestStr = "";
                for (int innerIndex = 0; innerIndex < INNER_ITERATION; innerIndex++)
                    addTestStr += "*";
                stopWatch.stop();
            }
    
            for (int outerIndex = 0; outerIndex < OUTER_ITERATION; outerIndex++) {
                StopWatch stopWatch = new LoggingStopWatch("StringConcat");
                concatTestStr = "";
                for (int innerIndex = 0; innerIndex < INNER_ITERATION; innerIndex++)
                    concatTestStr.concat("*");
                stopWatch.stop();
            }
    
            for (int outerIndex = 0; outerIndex < OUTER_ITERATION; outerIndex++) {
                StopWatch stopWatch = new LoggingStopWatch("StringBufferConcat");
                concatTestSb = new StringBuffer();
                for (int innerIndex = 0; innerIndex < INNER_ITERATION; innerIndex++)
                    concatTestSb.append("*");
                stopWatch.stop();
            }
    
            for (int outerIndex = 0; outerIndex < OUTER_ITERATION; outerIndex++) {
                StopWatch stopWatch = new LoggingStopWatch("StringBuilderConcat");
                concatTestSbu = new StringBuilder();
                for (int innerIndex = 0; innerIndex < INNER_ITERATION; innerIndex++)
                    concatTestSbu.append("*");
                stopWatch.stop();
            }
    
        }
    View Code

    测试结果:
    Performance Statistics   2010-04-08 06:16:00 - 2010-04-08 06:16:30

    Tag Avg(ms) Min Max Std Dev Count
    StringAddConcat 9355.4 7860 10046 547.7 10
    StringBufferConcat 3.5 0 5 2.3 10
    StringBuilderConcat 2.0 0 5 2.4 10
    StringConcat 3.1 0 6 2.5 10


  • 相关阅读:
    快速找到由程序员到CTO发展道路上的问路石
    从大师身上反思
    你真的了解企业虚拟化吗?
    “驱网核心技术丛书”创作团队访谈
    程序员到CTO需要准备什么
    深入搜索引擎的关键——索引
    程序员到CTO必须注意的几个关键点
    微软全球MVP教你如何规划程序人生
    “碟中碟”虚拟光驱软件开发者——万春 读《寒江独钓——Windows内核安全编程 》有感
    常用jar包之commonscollection使用
  • 原文地址:https://www.cnblogs.com/kissfu/p/4105635.html
Copyright © 2011-2022 走看看