最近看了篇关于javascript字符串链接的文章,里面提出了一种通过数组来进行字符串连接的方式:
- function StringBuffer() {
- this.data = new Array();
- }
- StringBuffer.prototype.append = function(str) {
- this.data.push(str);
- return this;
- }
- StringBuffer.prototype.toString = function(){
- return this.data.join("");
- }
- var date1 = new Date();
- var str = "";
- for(i = 0; i < 10; i++) {
- for(j = 0; j < 10000; j++) {
- str += "aaaaa";
- }
- }
- var date2 = new Date();
- document.getElementById("a").innerHTML = (date2.getTime() - date1.getTime());
- date1 = new Date();
- var strBuffer = new StringBuffer();
- for(i = 0; i < 10;i++) {
- for(j = 0; j < 10000; j++) {
- strBuffer.append("aaaaa");
- }
- }
- var result = strBuffer.toString();
- date2 = new Date();
- document.getElementById("b").innerHTML = (date2.getTime() - date1.getTime());