JS性能举例(连接字符串)

    var startTime = new Date().valueOf();
    var s = "";
    for (var i = 0; i < 10000; i++) {//用加号进行连接
      s += "This is a test string";
    }
    return new Date().valueOf() - startTime;
  }

  function goodTest() {
    var startTime = new Date().valueOf();
    var stringBuffer = new Array();
    for (var i = 0; i < 10000; i++) {
      stringBuffer.push("This is a test string");//用数组自带的push()方法
    }
    var s = stringBuffer.join("");
    return new Date().valueOf() - startTime;
  }

  function betterTest() {
    var startTime = new Date().valueOf();
    var stringBuffer = new Array();
    for (var i = 0; i < 10000; i++) {
      stringBuffer[stringBuffer.length] = "This is a test string";
    }
    var s = stringBuffer.join("");
    return new Date().valueOf() - startTime;
  }

 document.write(badTest()+"<br />");
 document.write(goodTest()+"<br />");
 document.write(betterTest()+"<br />");

 

posted @ 2016-04-17 08:54  绯乐  阅读(197)  评论(0编辑  收藏  举报