StringBuffer对象和传统的字符串连接方法性能测试比较

    技术2022-05-11  46

    <script language="javascript" type="text/javascript">

      function StringBuffer(){

         this._strings_=new Array;

       };

      

       StringBuffer.prototype.append=function(str){

          this._strings_.push(str);

        };

        StringBuffer.prototype.toString=function(){

          return this._strings_.join("");

        };

     

      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");

      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("<br />Concatenation with StringBuffer:"+(d2.getTime()-d1.getTime())+"milliseconds");

    </script>

    测试结果:

    Concatenation with plus: 11844millisecondsConcatenation with StringBuffer:156milliseconds

    这段代码对字符串连接进行两个测试,第一个使用加号,第二个使用StringBuffer类。每个操作都连接10000个字符串。日期值d1d2用于判断完成操作需要的时间。记住,创建新Date对象时,如果没有参数,赋予对象的是当前的日期与时间。要计算连接操作历经多少时间,把日期的毫秒表示(getTime()方法的返回值)相减即可。这是衡量JavaScript性能的常用方法。该测试的结果应该说明使用StringBuffer类比使用加号节省了100~200%的时间。

    摘自:《javascript高级程序设计》

    http://book.csdn.net/bookfiles/110/1001103141.shtml

     

    最新回复(0)