Hacker News new | ask | show | jobs
by pcwalton 3855 days ago
Singletons are fine, but it's almost always better to lazily initialize them rather than eagerly, to save on startup time. As a bonus, if you have no eager global initialization in your language, you can make import completely side-effect-free, which is a really nice simplification that I wish more languages adopted.
1 comments

The slow startup from imports is my biggest annoyance with python.

We had a decent sized library at a previous company that pulled in modules that defined huge register maps, wrapped c++ libraries, etc.

I wrapped all imports in a lazy importer that was triggered by the first attribute access. It brought our script startup times from 3 seconds down to a fraction.

Blows me away that this isn't default behavior for ALL modules.

That behaviour feels to me like it may result in faster startup, but would also result in less predictable performance for code bases with somewhat random access such as web applications.

You could I suppose do some cache warming to make sure the first user request isn't slowed down, but its one more thing to think about.

>"I wrapped all imports in a lazy importer that was triggered by the first attribute access."

Well, putting code in the root of your file is generally the problem to such things, I would argue. Granted, I don't know about how that is necessary when it comes to "register maps" and "wrapped c++ libraries". But I'd imagine you should be encapsulating them away anyways and that would include fixing large startup time by design.

If this was the default, any change could completely upend the initialization order of your app. "Explicit is better than implicit".