sitelink1 | |
---|---|
sitelink2 | |
sitelink3 | |
sitelink4 | http://1 |
extra_vars4 | ko |
extra_vars5 | http://www.javascriptkit.com/javatutors/closuresleak/index3.shtml |
extra_vars6 | sitelink1 |
All of the patterns shown below are described in detail in Justing's article. I'm going through them just for the sake of completeness:
[Exhibit 5 - Circular reference because of expando property]·미리보기 | 소스복사·
- <html>
- <head>
- <script type="text/javascript">
- var myGlobalObject;
- function SetupLeak(){
- //Here a reference created from the JS World
- //to the DOM world.
- myGlobalObject=document.getElementById("LeakedDiv");
- //Here DOM refers back to JS World;
- //hence a circular reference.
- //The memory will leak if not handled properly.
- document.getElementById("LeakedDiv").expandoProperty=
- myGlobalObject;
- }
- </script>
- </head>
- <body onload="SetupLeak()">
- <div id="LeakedDiv"></div>
- </body>
- </html>
Here the global variable myGlobalObject
refers to the DOM element LeakDiv
; at the same time LeakDiv
refers to the global object through its expandoProperty
. The situation looks like this:
The above pattern will leak due to the circular reference created between a DOM node and a JS element.
Since the JScript garbage collector is a mark and sweep GC, you may think that it would handle circular references. And in fact it does. However this circular reference is between the DOM and JS worlds. DOM and JS have separate garbage collectors. Therefore they cannot clean up memory in situations like the above.
Another way to create a circular reference is to encapsulate the DOM element as a property of a global object:
[Exhibit 6 - Circular reference using an Encapsulator pattern]·미리보기 | 소스복사·
- <html>
- <head>
- <script type="text/javascript">
- function Encapsulator(element){
- //Assign our memeber
- this.elementReference = element;
- // Makea circular reference
- element.expandoProperty = this;
- }
- function SetupLeak() {
- //This leaks
- new Encapsulator(document.getElementById("LeakedDiv"));
- }
- </script>
- </head>
- <body onload="SetupLeak()">
- <div id="LeakedDiv"></div>
- </body>
- </html>
Here is how it looks like:
However, the most common usage of closures over DOM nodes is event attachment. The following code will leak:
[Exhibit 7 - Adding an event listener as a closure function]·미리보기 | 소스복사·
- <html>
- <head>
- <script type="text/javascript">
- window.onload=function(){
- // obj will be gc'ed as soon as
- // it goes out of scope therefore no leak.
- var obj = document.getElementById("element");
- // this creates a closure over "element"
- // and will leak if not handled properly.
- obj.onclick=function(evt){
- ... logic ...
- };
- };
- </script>
- </head>
- <body>
- <div id="element"></div>
- </body>
- </html>
Here is a diagram describing the closure which creates a circular reference between the DOM world and the JS world.
The above pattern will leak due to closure. Here the closure's global variable obj
is referring to the DOM element. In the mean time, the DOM element holds a reference to the entire closure. This generates a circular reference between the DOM and the JS worlds. That is the cause of leakage.
When we remove closure we see that the leak has gone:
[Exhibit 8- Leak free event registration - No closures were harmed]·미리보기 | 소스복사·
- <html>
- <head>
- <script type="text/javascript">
- window.onload=function(){
- // obj will be gc'ed as soon as
- // it goes out of scope therefore no leak.
- var obj = document.getElementById("element");
- obj.onclick=element_click;
- };
- //HTML DOM object "element" refers to this function
- //externally
- function element_click(evt){
- ... logic ...
- }
- </script>
- </head>
- <body>
- <div id="element"></div>
- </body>
- </html>
Here is the diagram for the above code piece:
This pattern will not leak because as soon as the function window.onload
finishes execution, the JS object obj
will be marked for garbage collection. So there won't be any reference to the DOM node on the JS side.
And the last but not the least leak pattern is the "cross-page leak":
[Exhibit 10 - Cross Page Leak]·미리보기 | 소스복사·
- <html>
- <head>
- <script type="text/javascript">
- function LeakMemory(){
- var hostElement = document.getElementById("hostElement");
- // Do it a lot, look at Task Manager for memory response
- for(i = 0; i < 5000; i++){
- var parentDiv =
- document.createElement("<div onClick='foo()'>");
- var childDiv =
- document.createElement("<div onClick='foo()'>");
- // This will leak a temporary object
- parentDiv.appendChild(childDiv);
- hostElement.appendChild(parentDiv);
- hostElement.removeChild(parentDiv);
- parentDiv.removeChild(childDiv);
- parentDiv = null;
- childDiv = null;
- }
- hostElement = null;
- }
- </script>
- </head>
- <body>
- <input type="button"
- value="Memory Leaking Insert" onclick="LeakMemory()" />
- <div id="hostElement"></div>
- </body>
- </html>
Since we observe memory leakage even in Exhibit 1, it is not surprising that this pattern leaks. Here is what happens: When we append childDiv
to parentDiv
, a temporary scope from childDiv
to parentDiv
is created which will leak a temporary script object. Note that document.createElement("<div onClick='foo()'>");
is a non-standard method of event attachment.
Simply using the "best practices" is not enough (as Justing has mentioned in his article as well). One should also adhere to standards as much as possible. If not, he may not have a single clue about what went wrong with the code that was working perfectly a few hours ago (which had just crashed unexpectedly).
Anyway, let us re-order our insertion. The code below will not leak:
[Exhibit 11 - DOM insertion re-ordered - no leaks]·미리보기 | 소스복사·
- <html>
- <head>
- <script type="text/javascript">
- function LeakMemory(){
- var hostElement = document.getElementById("hostElement");
- // Do it a lot, look at Task Manager for memory response
- for(i = 0; i < 5000; i++){
- var parentDiv =
- document.createElement("<div onClick='foo()'>");
- var childDiv =
- document.createElement("<div onClick='foo()'>");
- hostElement.appendChild(parentDiv);
- parentDiv.appendChild(childDiv);
- parentDiv.removeChild(childDiv);
- hostElement.removeChild(parentDiv);
- parentDiv = null;
- childDiv = null;
- }
- hostElement = null;
- }
- </script>
- </head>
- <body>
- <input type="button"
- value="Memory Leaking Insert" onclick="LeakMemory()" />
- <div id="hostElement"></div>
- </body>
- </html>
We should keep in mind that, although it is the market leader, IE is not the only browser in the world. And writing IE-specific non-standard code is a bad practice of coding. The counter-argument is true as well. I mean, saying "Mozilla is the best browser so I write Mozilla-specific code; I don't care what the heck happens to the rest" is an equally bad attitude. You should enlarge your spectrum as much as possible. As a corollary, you should write standards-compatible code to the highest extent, whenever possible.
Writing, "backwards compatible" code is "out" nowadays. The "in" is writing "forward compatible" (also known as standards compatible) code which will run now and in the future, in current and in future browsers, here and on the moon.
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
117 | User Agent 관련 Reference URL | 황제낙엽 | 2011.02.22 | 41 |
116 | 각 브라우저 별 User Agent 정보 | 황제낙엽 | 2011.02.22 | 823 |
115 | History of User Agent | 황제낙엽 | 2011.02.22 | 38 |
114 | Navigator 객체란? | 황제낙엽 | 2011.02.22 | 53 |
113 | Understanding User-Agent Strings | 황제낙엽 | 2011.02.22 | 76 |
112 | User Agent 정보 모음 | 황제낙엽 | 2011.02.22 | 7768 |
111 | ActiveX 설치 여부를 검사하는 스크립트 | 황제낙엽 | 2011.02.13 | 4053 |
110 | 자바스크립트 예약어 | 황제낙엽 | 2010.11.03 | 35 |
109 | YUI Logger(Yahoo) 를 동적으로 로드하는 북마크릿 | 황제낙엽 | 2010.10.03 | 25 |
108 | Javascript 를 사용하여 Binary File 읽기 | 황제낙엽 | 2010.09.29 | 500 |
107 | 크로스 브라우저를 위한 브라우저 검사 코드 | 황제낙엽 | 2010.08.27 | 86 |
106 | Dynatrace For Ajax Performance | 황제낙엽 | 2010.08.18 | 45 |
105 | javascirpt IME-Mode 설정하기 | 황제낙엽 | 2010.08.17 | 1112 |
104 | Iframe 내의 페이지 접근방법 | 황제낙엽 | 2009.11.12 | 59 |
103 | 외부 라이브러리 (.js) 의 바람직한 동적 로딩 (The best way to load external JavaScript) | 황제낙엽 | 2009.10.05 | 124 |
102 | 숫자값으로의 변환 형태 | 황제낙엽 | 2009.09.02 | 18 |
101 | Boolean 데이터 타입 | 황제낙엽 | 2009.09.02 | 16 |
100 | toString 변환 테이블 | 황제낙엽 | 2009.09.02 | 13 |
99 | URI 인코딩을 해야 하는 문자들 | 황제낙엽 | 2009.09.02 | 23 |
98 | 체인 생성자(생성자 체인), 프로토타입 체인 그리고 생성자 재지정 | 황제낙엽 | 2009.08.12 | 55 |