2008/02/01 10:36

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>




 

크리에이티브 커먼즈 라이선스
Creative Commons License
올블로그추천버튼 블코추천버튼 블로그뉴스추천버튼 믹시추천버튼 한RSS추가버튼 구글리더기추천버튼


이 포스팅이 도움이 되었다면 구글에서 관련 정보를 찾아 보세요 ^^


Trackback 0 Comment 2

Trackback : http://i-ruru.com/trackback/289 관련글 쓰기

  1. 2008/02/05 14:14 address edit & del reply

    비밀댓글입니다

    • Favicon of http://ruru.tistory.com BlogIcon 써니루루 2008/02/06 19:02 address edit & del

      사이트까지 직접 찾아오셔서 글 남겨주셔서 감사합니다.

      양질의 서비스와 진짜 블로거가 원하는 바를 이루는 서비스로 거듭나시길..

      새해福 많이 받으세요~