zoukankan      html  css  js  c++  java
  • 一个很好的String组合连接的方法(StringBuffer)

    //String类操作 (相当于C#中的StringBuilder类)
    function StringBuffer(){
        this.__strings = new Array;
    }
    StringBuffer.prototype.append = function(str){
        this.__strings.push(str);
    }
    StringBuffer.prototype.toString = function(){
        return this.__strings.join("");
    }

     


    测试代码如下:
     function Test(){
            var buffer = new StringBuffer();
            buffer.append("hello");
            buffer.append(" world!");
            alert(buffer.toString());
            var d1 = new Date();
            var str = "";
            for(var i = 0; i < 10000; i++){
                str += "text";
            }
            var d2 = new Date();
            document.write("Concatenation with plus:" + (d2.getTime() - d1.getTime()) + " milliseconds\n\r");
           
            var oBuffer = new StringBuffer();
            d1 = new Date();
            for(var i = 0; i< 10000; i++){
                oBuffer.append("text");
            }
            var sResult = oBuffer.toString();
            d2 = new Date();
            document.write("Concatenation with plus:" + (d2.getTime() - d1.getTime()) + " milliseconds");
        }


    结论:
    这段代码对字符串链接进行两个测试,第一个使用加号,第二个使用StringBuffer类。每个操作都连接10000个字符串。该测试的结果说明使用StringBuffer类比使用加号节省了50%~66%的时间;
  • 相关阅读:
    算法训练 P1103
    算法训练 表达式计算
    算法训练 表达式计算
    基础练习 时间转换
    基础练习 字符串对比
    Codeforces 527D Clique Problem
    Codeforces 527C Glass Carving
    Codeforces 527B Error Correct System
    Codeforces 527A Glass Carving
    Topcoder SRM 655 DIV1 250 CountryGroupHard
  • 原文地址:https://www.cnblogs.com/chy8219/p/931229.html
Copyright © 2011-2022 走看看