Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

늘보블로그

메모리 누수 본문

스터디로그/javascript

메모리 누수

개발자늘보 2021. 2. 8. 23:34

자바스크립트의 메모리 누수


메모리 누수가 발생하는 경우

  • 불필요한 객체 프로퍼티 참조: 아래의 경우 printProp1()가 test 참조 시 사용하지 않는 prop2까지 로딩해 메모리 낭비 -> 객체 참조 제한하기
// bad
function somethingLarge() {
    return new Array(1000000);
}
const test = {
    prop1: somethingLarge(),
    prop2: somethingLarge(),
};
function printProp1(obj) {
    console.log(obj["prop1"]);
}
printProp1(test);

// good
function somethingLarge() {
    return new Array(1000000);
}
const test = {
    prop1: somethingLarge(),
    prop2: somethingLarge(),
};
function printProp(prop) {
    console.log(prop);
}
printProp1(test["prop1"]);
  • DOM 메모리 누수: DOM 항목을 가리키는 변수가 이벤트 콜백 외부에 선언될 경우 해당 DOM을 제거하더라도 참조 상태가 유지되 메모리 낭비 -> 1) 변수 호출 위치 변경 2) 핸들러 해지
<div id="one">ONE</div>
<div id="two">TWO</div>

<!-- bad -->
<script>
    let one = document.getElementById("one");
    let two = document.getElementById("two");

    one.addEventListener("click", function () {
        two.remove();
        console.log(two); // 삭제 이후에도 html 출력
    });
</script>

<!-- good -->
<script>
    let one = document.getElementById("one");

    one.addEventListener("click", function () {
        let two = document.getElementById("two");
        two.remove();
    });
</script>

<script>
    let one = document.getElementById("one");
    let two = document.getElementById("two");

    one.addEventListener("click", function () {
        two.remove();
    });
    one.removeEventListener("click");
</script>

'스터디로그 > javascript' 카테고리의 다른 글

함수 2  (0) 2021.01.16
함수 1  (0) 2021.01.15
Number() vs. parseInt()  (0) 2021.01.09
원시 값과 객체  (0) 2021.01.02
객체리터럴 2  (0) 2020.12.21