Skip to content

Server rendering is slower with npm react #812

Closed
mishoo/UglifyJS
#928

Description

@plievone

I ran a few benchmarks on the server (modifying https://github.com/paulshen/react-bench to not use jsdom). The results were surprising, as the browserified react.js was about 30% faster than the npm version, even with NODE_ENV=production.

The performance ranking (test run time) was react.min.js < react.js < NODE_ENV=production node react < node react.

I suspect process.env is not a regular js object but perhaps a getter and thus carries a penalty when you test for "production" !== process.env.NODE_ENV everywhere.

Also the minified version might still perform best of all, as at least some time ago V8 used function source length (including comments) as a heuristic for function complexity / compilation time and thus affecting chances for optimization in some cases, but the effect might be negligible.

Activity

  1. plievone commented on Jan 5, 2014

    @plievone
    ContributorAuthor

    process.env is indeed not a regular object, but defined from the native side, so that may be the culprit for server rendering regression:
    https://github.com/joyent/node/blob/b922b5e/src/node.cc#L2326-L2335 and https://github.com/joyent/node/blob/b922b5e/src/node.cc#L2030-L2055
    So this introduced a getter in quite time-sensitive places (around invariants etc) in your otherwise clean codebase. Can you reproduce the issue? /cc @petehunt @benjamn

  2. ghost assigned on Jan 8, 2014
  3. plievone commented on Apr 6, 2014

    @plievone
    ContributorAuthor

    Lately I have been simply using a wrapped module

    var React;
    if (process.env.NODE_ENV !== 'production') {
      React = require('./react-with-addons-0.10.0.js');
    } else {
      React = require('./react-with-addons-0.10.0.min.js');
    }
    module.exports = React;

    Works great. You could consider switching npm package to some such scheme if there are no downsides.

  4. sophiebits commented on Apr 7, 2014

    @sophiebits
    Contributor

    My first attempt was to just add var __DEV__ = process.env.NODE_ENV !== 'production'; to the top of every file, but unfortunately uglify isn't smart enough to do dead code removal then. I wonder if we should have vendor/constants.js essentially make two copies of the code -- one for dev, one for prod, so

    function x() { return __DEV__; }
    module.exports = x();

    transforms into

    if (process.env.NODE_ENV !== 'production') {
      var x = function x() { return true; };
      module.exports = x();
    } else {
      var x = function x() { return false; };
      module.exports = x();
    }

    so we only pay the getter cost once (per module) at require time.

    @benjamn Is doing this easy with recast? It's not obvious to me if this.replace interacts well with cloning the AST.

  5. mridgway commented on May 16, 2014

    @mridgway
    Contributor

    I would love to see this get some attention. 30% improvement out of the box would be awesome. Is there a lot of work to do here?

  6. petehunt commented on May 16, 2014

    @petehunt
    Contributor

    I think eventually we will want people to do a build step for server rendering, i.e. webpack's --target node mode. Especially if people start expressing static asset dependencies as require() statements.

  7. syranide commented on May 17, 2014

    @syranide
    Contributor

    I'm using webpack and new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'}) was enough to solve it for me. Is there no such thing in browserify?

  8. andreypopp commented on May 17, 2014

    @andreypopp
    Contributor

    For browserify there's envify transform which automatically activates for react package. You just need to set NODE_ENV before bundling:

    NODE_ENV=production browserify app-which-requires-react.js
    

    Thus browserify also can be used for bundling for server rendering.

  9. karlmikko commented on Aug 6, 2014

    @karlmikko
    Contributor

    Call me all crazy, just had a left field idea. Could the transformer that builds the npm module create 2 complete copies of react? one for dev and one for production?

    In the the normal version of react var React = require('react') could you there look at the NODE_ENV and swap which module is returned? This way on server you only get the performance hit once;

  10. zpao commented on Aug 6, 2014

    @zpao
    Contributor

    That's not too crazy. It's a bit annoying from a build process though. I'd love to know what's happening at a larger scale in the node community. It seems like we shouldn't be the first people to encounter this in a larger scale.

    A couple other ideas…

    What if we set global.__DEV__ = process.env.NODE_ENV in our main module and leave __DEV__ in our code everywhere else. There's some obvious bad behavior there (setting globals). So we could do variants. Only set it when it's not already set. Change __DEV__ to something more unique at build time (__REACT__DEV__) and then set that. If we switch to webpack for building the browser bundles, then the DefinePlugin solution is super easy, and I'm sure there's a way to do this in browserify too.

    Another idea: Have a RuntimeEnvironment modules which memoizes process.env.NODE_ENV. This is sounding like something node should do itself, but the code @plievone linked to uses ObjectTemplate (which if I'm understand a bit of V8 right doesn't do any caching because values can change). There would still be a lookup cost, but it would just be a property access, not a getter and not a call out to get current environment variables (getenv). This one is trickier because it would mean more code and we won't do this internally. I'd prefer a different solution, even if it's more hacky.

    If all you're using is React and nothing from react/lib/*, then you could do something like @plievone mentioned above. We started shipping the browerified bundles in the npm package, so require('react/dist/react') and require('react/dist/react.min') will end up giving you the bundles which don't access process.env.

  11. sophiebits commented on Apr 1, 2015

    @sophiebits
    Contributor

    I don't think we're going to do anything specifically for server rendering other than bundling the builds in dist like @zpao mentioned, but we might change the npm package eventually to be prebuilt using closure or similar.

  12. 37 remaining items

  13. STRML commented on Jan 19, 2016

    @STRML
    Contributor

    Just everyone using React in combination with webpack or browserify and not using the dist/ build.

    Alternatively they could use the DefinePlugin to set __DEV__ to false to get the dead code elimination.

  14. mhart commented on Jan 19, 2016

    @mhart
    Contributor

    @spicyj just to clarify, do you mean "everyone using React who also currently uses UglifyJS with it"?

  15. mhart commented on Jan 19, 2016

    @mhart
    Contributor

    Just so I'm clear, there are a few users here that I can think of. Those, on the browser:

    1. Using require('react/dist/...') everywhere already, or as a global <script>
    2. Using browserify/webpack + envify/DefinePlugin
    3. Using browserify/webpack + envify/DefinePlugin + UglifyJS
    4. Using browserify/webpack + plugin to transform require('react') to require('react/dist/...') or window.React

    So 1 and 4 are taken care of by the compilation in dist. What's the main reason for even supporting 2 and 3? Is it because of things like require('react/lib/...')?

  16. sophiebits commented on Jan 19, 2016

    @sophiebits
    Contributor

    2 and 3 are the most natural for many people. If you are using browserify then envify gets used automatically because of our config in package.json. Almost everyone minifies their code in prod.

    It is true that we could recommend #4 instead for many cases, but it does fall apart in the case of requiring submodules. We don't support this for external users because we consider the modules private but the addons packages use this pattern. Various third-party projects (unsupported by us) also make use of this.

  17. mhart commented on Jan 19, 2016

    @mhart
    Contributor

    I think the only reason 2 and 3 are "most natural" is just because process.env is used everywhere so you have to use something just to get it to even work out of the box. It would be equally easy to setup the config in package.json to use literalify or browserify-shim or whatever.

    I use 4 whenever I can and it's no more complicated than 2 or 3 for normal usage – I guess it's just a pity that users are encouraged to "reach in" to react/lib/ for various addons.

    Thanks for the clarification.

    So it's those doing 3 who are expecting their current UglifyJS setup to eliminate any code using __DEV__ that you're concerned about?

  18. sophiebits commented on Jan 19, 2016

    @sophiebits
    Contributor

    I guess it's just a pity that users are encouraged to "reach in" to react/lib/ for various addons.

    To clarify: we recommend users require react-addons-transition-group or similar, which (currently) reaches into react but that's an implementation detail.

    So it's those doing 3 who are expecting their current UglifyJS setup to eliminate any code using __DEV__ that you're concerned about?

    Yes.

  19. mhart commented on Jan 19, 2016

    @mhart
    Contributor

    we recommend users require react-addons-transition-group or similar

    Ah cool, good to know.

  20. added a commit that references this issue on Jan 26, 2016
  21. santiagoaguiar commented on Jul 29, 2016

    @santiagoaguiar

    We have been bitten by this one too. Would be great if some note about this behavior was present on https://facebook.github.io/react/docs/environments.html , it's a large performance impact, and is hard to find this issue unless you have already done all the investigation work.

  22. pmoleri commented on Jul 29, 2016

    @pmoleri

    I would like to add that this issue also affects Electron applications.

    Now the work arounds seem to be:

    • Include the minified version of React globally via <script> tag, it would only work in Electron and it isn't the node way, where one should be able to track every used object just seeing the requires. It also makes it difficult to switch between dev/prod.
    • Use the proposed hack to replace process.env with a regular object. Not good, as we are forced to overwrite node api just because we want to use React.
    • If using babel: transform-inline-environment-variables... by default babel doesn't transpile node_modules, this can be configured but doesn't look like a work around.

    Note that replace every require() to react/dist/react.min.js isn't a solution because react-dom automatically requires from react root, not from react/dist.

    Why is this issue closed?
    It seems to me that React should be able to initialize its configuration using NODE_ENV, then rely on its own objects, and optionally offer a React.setProduction(true/false) function to change the value later.
    Is there any reason why this wouldn't work?

  23. STRML commented on Jul 29, 2016

    @STRML
    Contributor

    Technically this could be fixed now as UglifyJS supports /* @const */ annotations, and it may be easier still as the team moves the build to Rollup in #7178.

    In combination with Rollup, it would be simple to export a __DEV__ var from a constants file and have it effectively tagged by Uglify for dead code elimination in production mode.

  24. jknight12882 commented on Dec 23, 2016

    @jknight12882

    Adding my two cents here, I was able to work around this by adding the following to the top of my server.js

    if (process.env.NODE_ENV === 'production') {
        require('react/dist/react.min.js');
        require.cache[require.resolve('react')] = require.cache[require.resolve('react/dist/react.min.js')];
    
        require('react-dom/dist/react-dom-server.min.js');
        require.cache[require.resolve('react-dom/server')] = require.cache[require.resolve('react-dom/dist/react-dom-server.min.js')];
    }
    

    I had previously wrapped React using local modules file://... as was suggested above, but this caused a lot of issues with npm shrinkwrap. This seems to get the job done without too much overhead or complexity.

  25. rtsao commented on Feb 10, 2017

    @rtsao

    For future reference, the above snippet is broken per: #8788

  26. STRML commented on Mar 8, 2017

    @STRML
    Contributor

    Referencing facebook/fbjs#86 which will fix this now that UglifyJS can properly eliminate dev code (even if it references a var that never changes) with its new reduce_vars option, which is a default.

    See facebook/fbjs#86 (comment) for more context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions