ruby-on-railsrubyeager-loading

What's the impact of eager_load=true?


I need to know why eager_load is preferred to be false in non-production environments? One of the arguments that I have heard of says that eager_load eager loads most of Rails and application in memory. Hence using eager_load for individual test makes it run slower. However this raises some questions like how does a test run without loading Rails and application related code? What is the Rails and application related code that is being eager loaded? config.eager_load_namespaces gives the following classes:

ActiveSupport
ActionDispatch
ActiveModel
ActionView
ActionController
ActiveRecord
ActionMailer
Jquery::Rails::Engine
MyApp::Application

Are all of these classes and their subclasses being eager loaded?

What are the clear disadvantages of using eager_load = false in development or testing environment?


Solution

  • However this raises some questions like how does a test run without loading Rails and application related code?

    The test loads the necessary code on demand as it tries to use it. So for example on some code line the test wants to use the ActiveRecord class. With eager_load set to false this class is not required yet, which will lead to an exception on a vanilla ruby program. Within a rails project however the test will require ActiveRecord on demand as it uses it. So at the end a single test runs faster, because only the code parts it needed have been required.

    This technique is the opposite of eager loading and it's called autoloading

    What is the Rails and application related code that is being eager loaded?

    Check out https://github.com/rails/rails. It's a bunch of stuff.

    Are all of these classes and their subclasses being eager loaded?

    yes

    What are the clear disadvantages of using eager_load = false in development or testing environment?

    In development environment it's an advantage and a best practice as you get faster boot times (neglected when using a preloader like spring). Probably it's also easier for reloading changes along with the cache_classes=false option, as you have less to reload (just an assumption).

    In test environment sometimes you just can't use eager_load=false if you want to estimate some code metrics like code coverage or doing style checks. E.g. simple_cov requires you to eager load all the code before starting tests.

    And in general it can happen that some library can't be used with eager loading because it does some initialization on loading a class which has to be already available even before calling its methods. However this is a rare case, having said that, it happened to us with the neo4j.rb gem