FLYNNLABAboutMeCodingActivityStudy 2024초등수학
NgZone
angular, ngzone

Performance Issue

AngularJS가 크게 성공했지만 항상 따라다니는 꼬리표가 생산성은 좋은데 성능이 떨어진다였다. TwoWay Binding의 패러다임의 장점과 동시에 단점이 있는 기술로 인식이 되었다. 이를 교훈 삼아 Angular는 NgZone이라는 방식을 도입했다.

IDEA

Angular는 비동기 상황에서 UI가 업데이트 되기 위한 조건은 다음과 같이 정의했다.

  • User Event: addEventListner
  • Ajax: XMLHttpRequest
  • Timer: setTimeout / setInterval

위 메서드를 monkey patch해서 UI 업데이트 상황을 제한

With Third Party Library

비동기 처리 콜백이 위 세가지 조건이 아닌 상황에서 발생시 UI업데이트가 되기 위해서는 run 메서드를 사용한다.

thirdPartyLibrary.asyncTask(result => {
  this.ngZone.run(() => this.result = result);
});

More Performance

일부러 UI업데이트를 막을 수 있다. 아래 예제는 단순하지만 복잡한 사용자 이벤트가 발생할때(mousemove) 매번 UI업데이트를 한다는건 좋은 전략이 아니다. 이때 runOutsideAngular 메서드를 활용한다.

result = 0;
    this.ngZone.runOutsideAngular(() => {
      // 여기서의 데이터 변경은 UI업데이트를 방지한다.
      setTimeout(() => {
        this.result = this.result + 200;
        setTimeout(() => this.ngZone.run(() => {
          this.result = this.result + 100;
        }), 2000);
      }, 1000);
    });

Resource