Search code examples
rubyimportrequirestandard-library

Does requiring from the standard library make a program slower?


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 required for use (and not just included outright)? So, specific questions:

  1. Does importing from the standard library make scripts slower?
  2. If so, is it always negligible, or does it depend on the package?
  3. What about third-party packages? Are they slower to import than the ones in the standard library?

Solution

  • 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.