Delay loading routes for rake tasks

I was benchmarking a simple rake task we have that is in a more critical path, and noticed that a good portion of the time is spent on loading/initializing routes.

Close to 19% of the execution is spend on routes_reloader, for a code that doesn’t use it.

This seems like an obvious low ranging fruit here, as most likely rake tasks don’t need any routes and for the eventuality someone is using them, that could be optionally eager_loaded! or could be lazy loaded when using something like a url_helper.

Does that make sense as a feature contribution? What are the main traps and gotchas I should be aware here?

1 Like

Here’s a roughly written plugin https://github.com/amatsuda/routes_lazy_routes that addresses the exact problem that you raised here.

The code is very much dirty and hackish since I couldn’t come up with any less tricky solution, but anyway it works and does what we expect (saves 5 seconds per each command execution in development / test env) in our real-world huge application. You can just bundle this, or of course it’d be nice if you could craft a cleaner patch for Rails :slight_smile:

2 Likes

I like your approach. In my case I need it to be available in “production” environment but can’t pay the price of the first slow request, so I will take inspiration on your code and try something slightly different.

My goal is to have it as a rails patch. I will report back as soon as I have something that minimally work.

Only require what you need for your rake task, not the entire :environment

task :mytask do
  require 'activerecord'
  # do stuff
end

1 Like