What is lazy initialization and why is it useful?

What is lazy initialization of objects? How do you do that and what are the advantages?


Solution 1:

Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.

One good example is to not create a database connection up front, but only just before you need to get data from the database.

The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.

Solution 2:

As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"

The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.

Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.