innerHTML 을 사용할 때 속도를 위한 주의사항



당연히 알고 있을 내용이지만..

아래 소스를 일단 분석해보면

1. 첫번째 붉은 코드는 div테그의 innerHTML에 직접 문자열을 추가해 나가고있고,

2. 두번째 붉은 코드는 먼저 문자열을 변수에 더해 담고, 전부 완료된 후 한번에 innerHTML에 넣고 있다.

innerHTML은 화면에 표시되는 브라우져 출력 버퍼에 내용이 보내지게 되는 Property(속성) 값이라 I/O 처리가 들어가게된다.
 
때문에 메모리에서 처리한 후 단 한번의 브라우져 출력 버퍼로 I/O를 수행하는 2번째 코드가

훨씬 빠른 성능을 낼 수 있다.

그러므로 반복구문(for, while)에 innerHTML에 값을 넣는 실수는 하지 않도록 하자.


예제 page. http://samples.msdn.microsoft.com/workshop/samples/author/perf/tip2.htm

<HTML>
<HEAD>
<TITLE>Performance Tip 2 - Batch Updates</TITLE>
<SCRIPT LANGUAGE="JScript">
function slow()
{
var start = new Date();

// Start processing
 divUpdate.innerHTML = "";
 for ( var i=0; i<100; i++ )
 {
  divUpdate.innerHTML += "<SPAN>This is a slower method! </SPAN>";
 }
// End processing

var end = new Date();
 spnSlow.innerText = "Slow method took " + (end.getTime()-start.getTime()) + " milliseconds.";
}

function faster()
{
var start = new Date();

// Start processing
 var str="";
 for ( var i=0; i<100; i++ )
 {
  str += "<SPAN>This is faster because it uses a string! </SPAN>";
 }
 divUpdate.innerHTML = str;
// End processing

var end = new Date();
 spnFaster.innerText = "Faster method took " + (end.getTime()-start.getTime()) + " milliseconds.";
}
</SCRIPT>
</HEAD>
<!-- TOOLBAR_START --><!-- TOOLBAR_EXEMPT --><!-- TOOLBAR_END -->
<BODY>

<H1>Performance Tip 1 - Batch Updates</H1>

<P>The slow method invokes the HTML parser each time the <B>innerHTML</B> property is set. To improve performance, a string can be built which is then assigned to the <B>innerHTML</B> property. </P>
<P>Click the buttons to see the difference in performance.</P>

<span>Slow -</span>
<BUTTON ONCLICK="slow()">innerHTML </BUTTON>&nbsp;
<SPAN ID="spnSlow" class="timertext"></SPAN>

<BR/><BR/>

<span>Fast -</span>
<BUTTON ONCLICK="faster()" >innerHTML using a string</BUTTON>&nbsp;
<SPAN ID="spnFaster"></SPAN>

<DIV ID="divUpdate"></DIV>

<!-- Copyright --><A HREF="http://www.microsoft.com/isapi/gomscom.asp?TARGET=/info/cpyright.htm" TARGET="_top">&copy; 2007 Microsoft Corporation. All rights reserved. Terms of use.</A></BLOCKQUOTE></BODY>
</HTML>