Thursday, 4 July 2013

Building strings in javascript

Instead of StringBuilder, we use an array and just append to the end of array.

http://trephine.org/t/index.php?title=Efficient_JavaScript_string_building


http://dev.opera.com/articles/view/efficient-javascript/?page=2#primitiveoperator

/**
* Constructs an html string from any number of lists of data items.
*/
function buildList( /* list1, list2, ... */ ) {
var buf = [ "<ul>\n" ];
for (var i=0; i<arguments.length; i++) {
var list = arguments[i];
for (var j=0; j<list.length; j++) {
buf[buf.length] = "<li>"; // append <li> tags and
buf[buf.length] = list[j]; // item to array buffer, utilizing
buf[buf.length] = "</li>\n"; // primitive array assignment
}
}
buf[buf.length] = "</ul>";
return buf.join('');
}