[JS] 메모리 릭(Memory Leak)

javaScript 기초를 탄탄하게 다져보자

Posted by lim.Chuck on December 24, 2024

[JavaScript]

기초

  1. [JS] Js기초
  2. [JS] Js기초 변수
  3. [JS] Js기초 자료형
  4. [JS] Js기초 형변환
  5. [JS] Js기초 연산자
  6. [JS] Js기초 반복문
  7. [JS] Js기초 switch
  8. [JS] Js기초 function
  9. [JS] Js기초 객체
  10. [JS] Js기초 배열

중급

  1. [JS] Js중급 호이스팅(Hoisting)과 TDZ(Temporal Dead Zone)
  2. [JS] Js중급 생성자함수
  3. [JS] 객체 메소드(Object methods), 계산된 프로퍼티(Computed property)
  4. [JS] 심볼(Symbol)
  5. [JS] WeakMap WeakSet
  6. [JS] 숫자, 수학 method (Number, Math)
  7. [JS] 문자열 메소드(String methods)
  8. [JS] 배열 메소드(Array methods)
  9. [JS] 구조 분해 할당 (Destructuring assignment)
  10. [JS] 매개변수 리스트와 전개 문법(Rest parameters and spread syntax)
  11. [JS] 클로저(Closure)
  12. [JS] setTimeout / setInterval
  13. [JS] call / apply / bind
  14. [JS] 상속, 프로토타입(Prototype)
  15. [JS] 클래스(Class)
  16. [JS] 클로미스(Promise)
  17. [JS] 비동기 처리(Async/Await)
  18. [JS] Generator
  19. [JS] 메모리 릭(Memory Leak)

메모리 릭(Memory Leak) 총정리 🔍

1. 메모리 릭이란?

프로그램에서 더 이상 필요하지 않은 메모리가 해제되지 않고 계속 남아있는 현상입니다.

2. 주요 발생 원인 ⚠️

  1. 이벤트 리스너 미제거

    1
    2
    3
    4
    5
    6
    7
    
    // 나쁜 예시
    element.addEventListener("click", handler);
    // 제거 안함
    
    // 좋은 예시
    element.addEventListener("click", handler);
    element.removeEventListener("click", handler);
    
  2. 타이머 함수 미정리

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    // 나쁜 예시
    setInterval(() => {
      // 작업
    }, 1000);
    
    // 좋은 예시
    const intervalId = setInterval(() => {
      // 작업
    }, 1000);
    clearInterval(intervalId); // 필요없을 때 정리
    
  3. 불필요한 데이터 보관

    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. 컴포넌트 정리

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    // React 예시
    useEffect(() => {
      const timer = setInterval(() => {}, 1000);
    
      // 정리 함수
      return () => {
        clearInterval(timer);
      };
    }, []);
    
  2. 이벤트 관리

    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. 주의사항 🚨

  1. 컴포넌트나 페이지 이동 시 정리함수 호출하기
  2. 큰 데이터는 사용 후 즉시 정리하기
  3. 전역 변수 사용 최소화하기
  4. 이벤트 리스너는 반드시 제거하기
  5. setInterval/setTimeout 사용 후 정리하기

5. 메모리 릭 탐지 방법 🔎

  1. Chrome DevTools - Memory 탭 사용
  2. Performance 모니터링
  3. 개발 도구의 메모리 사용량 관찰

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 = [];
  }
}

이렇게 메모리를 잘 관리하면 프로그램의 성능과 안정성을 높일 수 있습니다! 😊