자바스크립트의 메모리 누수
메모리 누수가 발생하는 경우
- 불필요한 객체 프로퍼티 참조: 아래의 경우 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>