Home >Web Front-end >JS Tutorial >JavaScript string connection performance optimization_javascript skills

JavaScript string connection performance optimization_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:57:221070browse
Copy code The code is as follows:

var str = "hello";
str = "world" ;

Background work:
1) Create a string to store "hello" and make str point to it.
2) Create a string to store "world".
3) Create a string to store the result.
4) Copy the current content in str to the resulting string.
5) Copy world into the result string.
6) Update str so that str points to the result string.
Every time a string is spliced, 2)~6) are repeated in a loop. If repeated hundreds or thousands of times, it will consume a lot of resources and affect performance.
Solution:
Use an Array object to store the string, and then use the join() method to output the result.
Modeled after the StringBuffer class in Java.
Copy code The code is as follows:

function StringBuffer(){
this._strings = new Array;
}
StringBuffer.prototype.append = function (str){
this._strings.push(str);
}
StringBuffer.prototype.toString = function (){
return this._strings.join("");
}

Test performance:
Code 1: Use "=" to concatenate strings
Copy code The code is as follows:

var d = new Date();
var str = "";
for(var i=0;i<10000;i ){
str = "test";
}
var d2 = new Date();
document.writeln(d2.getTime( )-d.getTime());

Code 2: Using StringBuffer
Copy code Code As follows:

var d = new Date();
var str = new StringBuffer();
for(var i=0;i<10000;i ){
str.append("test");
}
var res = str.toString();
var d2 = new Date();
document.writeln(d2.getTime()-d .getTime());

Judging from multiple test results, using StringBuffer can save more than 50% of time.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn