Swift: Watching lazy initializers in action

Applications face intrinsic memory and processing costs. Every object creation and every calculation adds to these costs. Using lazy initializers enables you to optimize performance by delaying expensive operations until they’re absolutely needed.

An object may never get around to using some property during its lifetime. By deferring creation you entirely save that cost. Or, consider a case where initialization is expensive. If you you spread out that cost over time, you have a lower peak demand across the app.

Lazy initializers move operations away from object creation to some point in the future. In Swift, you mark items with the @lazy attribute. This says “don’t perform this initialization until the property is explicitly requested”.

With playgrounds, you can see this attribute in action. In the following example, the lazyProperty does not exist until accessing the description property forces its creation. Once created, the property remains for the object lifetime but it’s also entirely possible for the object to never instantiate that property.

Screen Shot 2014-06-30 at 10.02.46 AM

Comments are closed.