When to use `require`, `load` or `autoload` in Ruby?
Generally, you should use require
. load
will re-load the code every time, so if you do it from several modules, you will be doing a lot of extra work. The lazyness of autoload
sounds nice in theory, but many Ruby modules do things like monkey-patching other classes, which means that the behavior of unrelated parts of your program may depend on whether a given class has been used yet or not.
If you want to make your own automatic reloader that loads your code every time it changes or every time someone hits a URL (for development purposes so you don't have to restart your server every time), then using load
for that is reasonable.
Apart from what others have already told you, future of autoload
is uncertain. It was scheduled to be deprecated in Ruby 2.0, but the deprecation wasn't made in time for the 2.0 feature freeze. It is now expected that autoload
will be deprecated in Ruby 2.1, but that is not even certain anymore.
here's what you gain with autoload
over require
:
autoload
is primarily for speeding up the initialization phase of your Ruby program or Rails application. By not loading the resources until they are needed, it can speed up things quite a bit.
Another advantage is that you may not need to load some parts of the code, if the user doesn't use certain features -- thereby improving load time and reducing the memory footprint.
mylibrary.rb
puts "I was loaded!"
class MyLibrary
end
Try in irb
irb(main):001:0> require 'mylibrary'
I was loaded!
=> true
irb(main):001:0> autoload :MyLibrary, 'mylibrary'
=> nil
irb(main):002:0> MyLibrary.new
I was loaded!
=> #<MyLibrary:0x0b1jef>
See the difference.