Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rails preloads all of its dependencies (gems) during boot time?

When Rails starts it preloads all of its dependencies (gems), which results in very slow startup time. In a medium sized project I'm working on, the start time of Rails is 10-15 seconds depends on the machine.

While this is not an issue in production, it is a huge pain in development. Specially when working TDD/BDD. There are solutions to speed up the tests (like spork), but they introduce issues of their own.

My question is: why not require the needed dependencies in each of the code files, instead of preloading everything during startup time?

What are the downsides of manual requires? The extra lines of code?

like image 372
arikfr Avatar asked Oct 03 '11 16:10

arikfr


1 Answers

Rails is not PHP. Some resources are autoloaded, but all of the ones that you're likely to need are loaded on boot/initialization because it is better to do so before requests are being made so the application is ready than to lazily load them on request, slowing down the first request. A lot of this last-minute on-the-fly definition of methods and loading of classes still happens, cutting down load time to a mere 10-15 seconds, but if you cut 5-10 seconds off of that load time, it'd just be tacked onto the first request. No good, right?

A lot of the load time you experience is in the gems/plugins/libraries that you add to your project. Many of significant size offer ways to load only the portions that you need, and plenty more could use this optimization. For example, if you have a Rails project that doesn't need Active Record, you can replace:

require 'rails/all'

…with:

require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"

…in your application.rb to cut back on loading (and avoid errors about the database not existing).

like image 143
coreyward Avatar answered Oct 15 '22 23:10

coreyward