2008년 06월 27일
Javascript String Performance
원본 : http://notesweb2.blogspot.com/2007/03/javascript-string-performance.html
Tuesday, March 20, 2007
Javascript String Performance
Followup previous article on innerHTML performance, I now take a look at what is the better way to built the HTML string for the innerHTML.
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 ThursdayAdd to del.icio.us
이 글과 관련있는 글을 자동검색한 결과입니다 [?]
- 배열 공부를 하면서 만든 프로그램... by 졸업하자
- Array in STATA by rapier
- [javascript / DOM scripting] optgroup 사용한 select boxes by syj8
# by | 2008/06/27 13:30 | Javascript | 트랙백 | 덧글(0)





☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]