Lazy vs. eager instantiation: Which is better?

Lazy vs. eager instantiation: Which is better?

When instantiating Java objects that are expensive in terms of resource usage, we don’t want to have to instantiate them every time we use them. It’s far better for performance to have a ready-to-use instance of the object that we can share across the system. In this case, the lazy instantiation strategy works very well.

Lazy instantiation has its drawbacks, however, and in some systems, a more eager approach is better. In eager instantiation, we usually instantiate the object once as soon as the application is started. Neither approach is all good or all bad: they are different. Each one works best in certain kinds of scenarios.

This article introduces you to these two ways to instantiate your Java objects. You’ll see code examples and then test what you’ve learned with a Java code challenge. We’ll also discuss the pros and cons of lazy instantiation versus eager instantiation.

To read this article in full, please click here