We know that the String type in java is a reference type. If you concatenate a String with + =, a new address is frequently allocated and directed to the new address block, which undoubtedly consumes system performance. The String type in javascript is similar to the String type in java. If we concatenate strings using ++ = in large quantities, the interface will lose response (stuck ).
Both java and. net provide StringBuffer () or StringBuilder () methods to achieve the efficiency of splicing large data volumes. What about javascript? How does it solve this problem? In fact, Arrays can be used in javascript to improve the splicing efficiency. The push () method of arrays is used to add data and the join () method of arrays is used to convert data into strings.
<script type="text/javascript">var strArr = new Array();strArr.push("aaaa");strArr.push("bbbb");strArr.push("ccccc");alert(strArr.join(' '));</script>
This method can greatly improve the splicing efficiency, but it has a small problem, that is, it cannot push continuously, for example: strArr. push ("aaa "). push ("bbb "). push ("ccc");, it cannot be implemented, does not conform to our programming habits, So we encapsulated a StringBuffer js class, making programming easier!
/*** @ Description: String concatenation * @ CreateTime: 2:42:35 * @ author: chenzw * @ version V1.0 */function StringBulider () {this. data = new Array ();}/*** concatenated string, which can be concatenated consecutively * @ return {} */StringBulider. prototype. append = function () {this. data. push (arguments [0]); return this;}/*** convert to string output * @ return {} */StringBulider. prototype. toString = function () {if (arguments. length> 0) {return this. data. join (arguments [0]);} else {return this. data. join ('') ;}}/*** determines whether the string array is empty * @ return {}*/StringBulider. prototype. isEmpty = function () {return this. data. length <= 0;}/*** clear String Array */StringBulider. prototype. clear = function () {this. data = []; this. data. length = 0 ;}
/*** Test Data */var sb = new StringBulider (); sb. append (""). append ("B "). append ("c "). append ("d"); alert (sb. toString (','); // result: a, B, c, d