concurrency - Is 'require' preferrable to 'autoload' with Ruby 2 in a multi-process fork server? -
i reading this article. concern benefits of autoload
vs require
. reading article, gather using autoload
multi-threaded servers bad because 1 thread might try load object not in memory yet.
the article says multi-process servers? autoload those? says depends. if server uses fork (which spawns new process each request), such phusion passenged, , using ruby 2, autoload not beneficial.
the reason because ruby 2 uses copy-on-write semantics. means better use require
autoload
. copy-on-write semantics, if load foo::bar
on boot, have 1 copy of foo::bar
shared between processes. hence, there no big memory footprint.
however, if not using ruby 2 , not using multi-process server uses fork, each process end loading own copy of foo::bar
possibly leading higher memory usage. therefore, in case autoload
preferrable require
.
is interpretation of article correct?
i think you've got it, restate couple of points clear:
the important distinction isn't quite between
require
,autoload
between eager , lazy loading. eager loading thread-safe , memory efficient when forking, slows server startup. lazy loading neither thread-safe nor memory efficent when forking, allows fast server startup.require
orautoload
railseager_autoload
eager load;autoload
lazy loads.with above in mind, different servers , ruby versions raise different issues lazy , eager loading:
- in threading server, lazy loading unsafe, eager loading (ahem) required.
- in evented server, lazy loading fine, might lazy-load fast server startup.
- in forking server, lazy loading safe memory-inefficient.
- in ruby < 2, eager loading memory-inefficient, since ruby < 2 doesn't support copy-on-write. might load lazily. (actually, should upgrade current ruby.)
- in ruby >= 2, eager loading memory-efficient, since takes advantage of copy-on-write, , therefore preferred.