[JavaScript]
기초
- [JS] Js기초
- [JS] Js기초 변수
- [JS] Js기초 자료형
- [JS] Js기초 형변환
- [JS] Js기초 연산자
- [JS] Js기초 반복문
- [JS] Js기초 switch
- [JS] Js기초 function
- [JS] Js기초 객체
- [JS] Js기초 배열
중급
- [JS] Js중급 호이스팅(Hoisting)과 TDZ(Temporal Dead Zone)
- [JS] Js중급 생성자함수
- [JS] 객체 메소드(Object methods), 계산된 프로퍼티(Computed property)
- [JS] 심볼(Symbol)
- [JS] WeakMap WeakSet
- [JS] 숫자, 수학 method (Number, Math)
- [JS] 문자열 메소드(String methods)
- [JS] 배열 메소드(Array methods)
- [JS] 구조 분해 할당 (Destructuring assignment)
- [JS] 매개변수 리스트와 전개 문법(Rest parameters and spread syntax)
- [JS] 클로저(Closure)
- [JS] setTimeout / setInterval
- [JS] call / apply / bind
- [JS] 상속, 프로토타입(Prototype)
- [JS] 클래스(Class)
- [JS] 클로미스(Promise)
- [JS] 비동기 처리(Async/Await)
- [JS] Generator
- [JS] 메모리 릭(Memory Leak)
메모리 릭(Memory Leak) 총정리 🔍
1. 메모리 릭이란?
프로그램에서 더 이상 필요하지 않은 메모리가 해제되지 않고 계속 남아있는 현상입니다.
2. 주요 발생 원인 ⚠️
-
이벤트 리스너 미제거
1 2 3 4 5 6 7
// 나쁜 예시 element.addEventListener("click", handler); // 제거 안함 // 좋은 예시 element.addEventListener("click", handler); element.removeEventListener("click", handler);
-
타이머 함수 미정리
1 2 3 4 5 6 7 8 9 10
// 나쁜 예시 setInterval(() => { // 작업 }, 1000); // 좋은 예시 const intervalId = setInterval(() => { // 작업 }, 1000); clearInterval(intervalId); // 필요없을 때 정리
-
불필요한 데이터 보관
1 2 3 4 5 6 7 8 9 10 11 12 13
// 나쁜 예시 const dataStore = []; function addData() { dataStore.push(newData); // 계속 쌓기만 함 } // 좋은 예시 function addData() { dataStore.push(newData); if (dataStore.length > 1000) { dataStore.splice(0, 100); // 오래된 데이터 정리 } }
3. 메모리 관리 방법 ✅
-
컴포넌트 정리
1 2 3 4 5 6 7 8 9
// React 예시 useEffect(() => { const timer = setInterval(() => {}, 1000); // 정리 함수 return () => { clearInterval(timer); }; }, []);
-
이벤트 관리
1 2 3 4 5 6 7 8 9 10
class EventManager { setup() { this.handler = this.handleEvent.bind(this); document.addEventListener("click", this.handler); } cleanup() { document.removeEventListener("click", this.handler); } }
4. 주의사항 🚨
- 컴포넌트나 페이지 이동 시 정리함수 호출하기
- 큰 데이터는 사용 후 즉시 정리하기
- 전역 변수 사용 최소화하기
- 이벤트 리스너는 반드시 제거하기
- setInterval/setTimeout 사용 후 정리하기
5. 메모리 릭 탐지 방법 🔎
- Chrome DevTools - Memory 탭 사용
- Performance 모니터링
- 개발 도구의 메모리 사용량 관찰
6. 좋은 코드 구조 예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class DataManager {
constructor() {
this.data = [];
this.timers = [];
}
start() {
const timer = setInterval(() => {
this.data.push(newData);
}, 1000);
this.timers.push(timer);
}
cleanup() {
// 타이머 정리
this.timers.forEach((timer) => clearInterval(timer));
this.timers = [];
// 데이터 정리
this.data = [];
}
}
이렇게 메모리를 잘 관리하면 프로그램의 성능과 안정성을 높일 수 있습니다! 😊