I’m thinking of ruby specifically when I ask this question, but if the answer is language-agnostic, I’d like to know as well.
I often require
from the ruby standard library, namely fileutils
, open3
, and pathname
.
But if I only need to use their capabilities in one or two lines, I avoid them and go for (sometimes less readable) alternatives that don’t need a require
.
However, using them doesn’t appear to hurt performance of my scripts, and even with quick benchmarks (using time
), things seem to run at the same speed they would if I used different methods. But it seems weird to me it would make no difference, because why then have them be require
d for use (and not just included outright)? So, specific questions:
Importing a library will take a non-zero amount of time, but the amount of time is directly proportional to what library. Some are very small, some much larger, but all of the ones that ship with Ruby are usually quick to load.
Unless you're running your script a thousand times a second the impact of a require
is going to be minimal.
It's usually better to get all the require
operations out of the way as early as possible to shake out any dependency problems, especially with gems. There's nothing worse than code that crashes because of a broken dependency, but only when you perform a particular action that doesn't happen often.
If you are starting this process thousands of times over, consider a tool like Spring or your own forking model to avoid the startup penalty. You can fork
a pre-configured process any number of times, each of which will be ready nearly instantaneously.