LoginSignup
77

More than 5 years have passed since last update.

Reactのサーバサイドレンダリングとパフォーマンスについてのメモ

Last updated at Posted at 2017-05-24

Reactのサーバサイドレンダリングとパフォーマンスについて調べてたのでメモ :pencil:

基本的なこと

サーバサイドとReactのproduction build

要約: Reactをサーバサイドで使うときも、クライアントサイドのように圧縮(というよりはcode eliminate)しないと遅い

Reactはdev向けのコードを大量に含んでいる。
これはprocess.env.NODE_ENV !== 'production'の時実行されるassertや警告などが主となりproductionには必要ない。
そのため、process.env.NODE_ENV = 'production'をしないとかなり不利な結果を得る。

I tend to agree that "compiling server side code with webpack to remove access to process" is not what Node developers would typically do, and likely many React users are not even aware of this possibility. So the current results are probably more representative of React SSR perf in the wild. However, it can also be a bit unfair to not show React's perf with full optimization.

サーバサイドもprocess.env.NODE_ENV === 'production'でuglifyしてdead codeを消し去ったReactを使うことでデバッグ情報がないものとなる。
Reactが公式で配っているbundle済みのもの(min.js)を使うのが手早い。

将来的には、Reactはdevとprodのbundleをそれぞれ配布しREACT_ENVでどちらを使うか設定出来るようになるかも とのこと。
(NODE_ENVも引き続き見る感じ)

パフォーマンス計測

デバッグ

node --inspect server.js で Chromeでプロファイルを取ってみる

  • CPU Profileを取る
  • "Chart"表示にすれば見慣れたタイムラインでプロファイルを読める

debug

最適化の種類

ちなみに一番最初にmemcachedではなく、Redisを使いました。しかし、Redisにおいてオブジェクトのサイズが10kbを超えて、特にevictionが発生するとパフォーマンスが急激に落ちます。そのため、途中memcachedに切り替えました。

現実的な解として

  • renderToStringが遅い問題をどうにかする必要がある
    • レンダリングするコンポーネントを減らす
    • 結果をキャッシュして返す
    • の2つが主と解となり両方を組み合わせる事が多い
  • キャッシュ
    • ユーザ情報を含んだrender結果をキャッシュすると問題がおきやすい
    • ユーザ情報だけサーバではrenderしないようにするコンポーネントの実装が必要になる

TODO:

  • renderToStringClusterで並列化するような事例もある?
  • キャッシュするにはユーザ情報をコンポーネントから隠すスイッチがいる

目安

レスポンスまで100ms以下

キャッシュされたページのレスポンスタイムは50ms以下になっています。

アメブロ2016 ~ Isomorphic JavaScriptの詳しい話 | CyberAgent Developers Blog | サイバーエージェント デベロッパーズブログ

事例

未来

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
77