[angular] 바인딩 메모리 누수 방지

Angular 애플리케이션을 개발할 때 자주 발생하는 문제 중 하나는 바인딩 메모리 누수(binding memory leaks)입니다. 바인딩 메모리 누수란 메모리에서 데이터가 해제되지 않고 계속 유지되는 현상을 의미합니다. 이러한 현상은 애플리케이션 성능에 악영향을 미치며, 메모리 누수가 계속되면 결국 애플리케이션의 충돌로 이어질 수 있습니다.

바인딩 메모리 누수가 발생하는 이유

주요한 이유 중 하나는 구독(subscription) 관리입니다. Observables을 활용하여 비동기 데이터를 구독하면, 해당 구독을 해제하지 않으면 메모리가 해제되지 않을 수 있습니다. 또한, 이벤트 핸들러(event handlers)를 올바르게 해제하지 않을 경우에도 메모리 누수가 발생할 수 있습니다.

바인딩 메모리 누수 방지 방법

1. 구독 관리

옵저버블 구독 시 반환되는 Subscription 객체를 활용하여 해당 컴포넌트가 destroy될 때 구독을 해제하는 방법을 사용할 수 있습니다.


import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataService } from './data.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-my-component',
  template: `
    <p>{{ data }}</p>
  `
})
export class MyComponent implements OnInit, OnDestroy {
  private dataSubscription: Subscription;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataSubscription = this.dataService.getData().subscribe(data => {
      this.data = data;
    });
  }

  ngOnDestroy() {
    this.dataSubscription.unsubscribe();
  }
}

2. 이벤트 핸들러 해제

이벤트 핸들러를 정의할 때에는 addEventListener로 정의하고, 컴포넌트가 destroy될 때 이벤트 핸들러를 해제하는 것이 좋습니다.

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    <button id="my-button">Click me</button>
  `
})
export class MyComponent implements OnInit, OnDestroy {

  ngOnInit() {
    document.getElementById('my-button').addEventListener('click', this.onClick);
  }

  ngOnDestroy() {
    document.getElementById('my-button').removeEventListener('click', this.onClick);
  }

  onClick(event: Event) {
    console.log('Button clicked');
  }
}

바인딩 메모리 누수를 줄이기 위해 구독 관리와 이벤트 핸들러 해제에 신경 써주는 것이 중요합니다. 메모리 누수를 방지하여 안정적이고 효율적인 Angular 애플리케이션을 구축할 수 있습니다.

참고문헌: Angular 공식 문서 - Angular 생명주기 훅