I use 2 for loop to built a table with 1000 rows and 5 columns. 4 different ways of building the string is tested. The test is done on Firefox 2.
1) str += ...
2) str = str + ...
3) str = str.concat(... , ...)
4) str.push(... , ...)
Below is the javascript sample for the 4th test cases
function init(){
console.time("String")
var newStr = new Array("<table>");
for(var i=0; i<1000; i++){
newStr.push("<tr>");
for (var j=0; j<5; j++){
newStr.push("<td>row ", i, " col ", j, "</td>");
}
newStr.push("</tr>");
}
newStr.push("</table>");
document.getElementById("content").innerHTML = newStr.join("");
console.timeEnd("String");
}
I did sample of 20 time and get the average result.
Test Type | Average Time (ms) | |
---|---|---|
1 | str += ... | 317.5 |
2 | str = str + ... | 285.4 |
3 | str = str.concat(... , ...) | 287.2 |
4 | str.push(... , ...) | 298.4 |
The results is quite close. The 1st Case is the slowest among all. The other 3 time is almost silimar considering their performance variation is about the same. Thus for most case (small functions), either way should be fine. But to squeeze every ms out, try using case 2-4.
The only thing to avoid is building the string like the example below.
newStr = newStr + "row ";
newStr = newStr + i;
newStr = newStr + " col ";
newStr = newStr + j;
newStr = newStr + "";
Use this instead:
newStr = newStr + "row " + i + " col " + j + "";
Any String that can be build in one line, should be done so.
Show-n-Tell Thursday Add to del.icio.us