Development Tip

React vs Angular : React를 사용한 느린 렌더링

yourdevel 2021. 1. 8. 22:29
반응형

React vs Angular : React를 사용한 느린 렌더링


Angular와 React를 비교하고 성능 테스트를 시도하여 두 프레임 워크에서 큰 (ish) 목록이 얼마나 빨리 렌더링되는지 확인하기로 결정했습니다.

기본적인 통화 형식으로 React 프로토 타입을 완성했을 때 빠른 노트북에서 렌더링하는 데 2 ​​초 정도 걸렸습니다. Angular를 사용하면 거의 눈에 띄지 않았습니다. 전화로 전환했을 때만 눈에 띄는 지연이있었습니다.

React가 성능을 위해 Angular의 바지를 이길 것이라고 들었 기 때문에 이것은 매우 놀랐지 만이 경우에는 그 반대 인 것 같습니다.

문제를 분리하기 위해 프로토 타입을 매우 간단한 앱으로 추출했습니다. https://github.com/pselden/react-render-test

이 샘플에서는 언어를 변경 한 후이 간단한 목록을 렌더링하는 데 거의 200ms가 걸리며 거의 아무것도하지 않습니다.

내가 여기서 뭔가 잘못하고 있니?

/** @jsx React.DOM */
'use strict';

var React = require('react'),
    Numbers = require('./Numbers');

var numbers = []
for(var i = 0; i < 2000; ++i){
    numbers.push(i);
}

var App = React.createClass({
    getInitialState: function() {
        return { locale: 'en-US' };
    },

    _onChangeLocale: function(event) {
        this.setState({locale: event.target.value});
    },

    render: function() {
        var currentLocale = this.state.locale;

        return (
            <div>
                <select
                    onChange={this._onChangeLocale}>
                    <option value="en-US">English</option>
                    <option value="fr-FR">French</option>
                </select>
                <Numbers numbers={numbers} locales={[currentLocale]} />
            </div>
        );
    }
});

module.exports = App;
/** @jsx React.DOM */
'use strict';

var React = require('react'),
    ReactIntlMixin = require('react-intl');

var Numbers = React.createClass({
    mixins: [ReactIntlMixin],

    getInitialState: function() {
        return {
            numbers: this.props.numbers
        };
    },

    render: function() {
        var self = this;
        var list = this.state.numbers.map(function(number){
            return <li key={number}>{number} - {self.formatNumber(number, {style: 'currency', currency: 'USD'})}</li>
        });

        return <ul>{list}</ul>;
    }
});

module.exports = Numbers;

추신 : 각도 버전 추가 : https://github.com/pselden/angular-render-test

편집 : react-intl로 문제를 열었고 조사한 결과 https://github.com/yahoo/react-intl/issues/27 사용시 그다지 오버 헤드 가 없다는 사실을 발견했습니다 -단순히 React 자체가 더 느립니다 여기.


이것은 확실히 흥미로운 테스트 케이스입니다.

타임 라인을 살펴보면 Angular가 단 20ms 만에 변경 이벤트 처리를 완료했음을 알 수 있습니다. 나머지 시간은 레이아웃과 다시 그리기에 사용됩니다.

각도 타임 라인

React (프로덕션 빌드 사용, 저장소는 기본적으로 dev 사용)에 약 59ms가 걸립니다. 다시 말하지만 나머지 시간은 레이아웃 및 다시 그리기에 사용됩니다.

반응 타임 라인

CPU 플레임 차트를 살펴보면 Angular가 훨씬 적은 작업을 수행하는 것으로 보입니다.

모난:

각도 CPU 그래프

반응 :

CPU 그래프 반응

React는 shouldComponentUpdate수천 개 중 하나의 구성 요소 인스턴스가 업데이트되고 다른 인스턴스는 동일하게 유지되어야 할 때 특히 유용한 형태로 꽤 좋은 최적화 후크를 제공합니다 . 이 데모 에서 사용하는 기술입니다 (시크릿 창에서 시도해보세요. 일부 Chrome 확장 프로그램이 레이아웃 / 다시 그리기 시간을 훨씬 더 높게 만드는 것을 발견했습니다. 목록이 1000 개가되면 단일 요소를 추가 / 제거하는 데 ~ 13ms가 걸립니다. 요소의 크기 / 색상을 변경하는 데는 ~ 1ms가 걸립니다). 그러나 모든 요소를 ​​업데이트해야 할 때는 좋지 않습니다.

내 생각에 Angular는 테이블의 대부분 또는 모든 요소를 ​​변경하는 데 더 빠르며 React는 .NET을 사용할 때 선택 항목을 업데이트하는 데 능숙 할 것 shouldComponentUpdate입니다.


아무도 PureRenderMixin을 언급하지 않았다는 것에 놀랐습니다 . 그것은 shouldComponentUpdate당신이 그것에 대해 걱정할 필요가 없도록 구현 됩니다.

또한 React Performance Tools 가 유용한 정보를 얻을 수 있는지 궁금 합니다.

그리고 저는 Ryan Florence의이 강연을 보고 Angular가 React보다 빠르다는 사실에 놀랐습니다 .


우리는 프레임 워크의 일부 속성을 분석하려고 시도했지만, 물론 이것은 전체 목록이 아닙니다. 아래에는 속성 비교에 대한 통합되고 중요한 표가 있습니다.

여기에 이미지 설명 입력

좀 더 자세한 내용을 살펴 보겠습니다.

여기에 이미지 설명 입력

여기에 이미지 설명 입력

Although Angular vs React differences are many, they can do the same thing, namely to build client interface. Both have their place. For those peoples who like web development above all interesting is innovative AngularJS approach to HTML.

AngularJS really is a full framework and not just a library, as the ReactJS, but ReactJS has better performance than the AngularJS by implementing virtual DOM. In our opinion, you should use AngularJS if:

  • you plan to carry a lot of unit tests during development,
  • you want a comprehensive solution for your application.

However, two-way data binding is often touted advantage of using AngularJS, but because it is implemented through a series digest, adding too much complexity for certain functions and expressions can lead to deterioration in performance of your applications.


In this particular case you need to be aware that the state trickles down and so do the DOM updates. What you want to do is create a Price component that stores the locale in its own state and receives a signal (ie channel or flux) to change the locale as opposed to sending the locale prop all the way down. The idea is that you don't need to update the entire Numbers component, just the prices inside. The component might look like:

var Price = React.createClass({
    mixins: [ReactIntlMixin],
    componentDidMount: function() {
        subscribeToLocal(this.onLocaleChange);
    },
    onLocaleChange: function(newLocales) {
        this.setState({locales: newLocales});
    },
    render: function() {
        return <span>this.formatNumber(this.props.number, this.state.locales, {style: 'currency', currency: 'USD'})</span>
    }
});

In React component, once you call setState, it will trigger the render function immediately. React will mark this component as dirty, and will re-render all the children element inside this component.

It will not render the whole Native DOM elements because of the Virtual DOM, thus it will still create new instances of its children ReactElements, which can lead to extra Javascript memory cost.

To avoid this issue, you need shouldComponentUpdate function which implemented in Component Class. it will executed before Render method. If you find the there is nothing changed right now, for instance in your example, you change the state.locale. You can definitely consider this component need no update. so just return false to prevent the render call.

This is a base solution to solve React performance issues. Try to add "shoudlComponentUpdate" in your Numbers Component to avoid tons of

  • element re-render


  • This is an example where all that is changing is one data output. It's not impossible that Angular's two way data-binding simply offers a faster re-render when all that is changing is the display of the bound data.

    React does not promise that its renders are faster than any other framework under all circumstances. What it does offer is the ability to handle ~arbitrarily complex DOM updates in very efficient manner, and offer a variety of lifecycle methods (e.g. componentWillReceiveProps, componentDidUpdate, in addition to the afore-mentioned shouldComponentUpdate) to let you fire callbacks on those events and control how and if they should happen. Here, there's very little to optimize, because all you are doing is changing 2,000 text displays.

    edit: To clarify, React is useful in doing more complex DOM manipulations because it's virtual DOM algorithm allows it to choose the minimal set of DOM operations necessary to update your DOM. That's still a lot of work to do when all that needs to be happening is 2000 instances of some text changing.

    참조 URL : https://stackoverflow.com/questions/26658302/react-vs-angular-slow-rendering-with-react

    반응형