How lazy are you?

Milan Brankovic
2 min readDec 27, 2019

Memory on the smartphone is limited, although we see that new phones are increasing memory size day by day. Most of developers nowadays do not care about memory anymore, like there is always an indefinite pool somewhere which they can claim. To overcome this problem, there is a technique which can defer allocation of memory to the point when it is actually needed. It's called lazy loading.

What is lazy loading?

Lazy loading is an optimization technique which delays loading of object(s) until the point of when it's needed.

For example, this technique is used for: infinity scroll, loading of the images on the web page, loading data from db, etc.

How can we do this in Swift?

Swift offers lazy keyword which delays loading until first time requested. Let's look at the example.

final class DataImporter {
lazy var data: [String] = {
// load the data here
}()
}

The DataImporter class has a property called data, which is/should hold array of String values. Although the rest of its functionality is not shown, the purpose of this DataImporter class is to manage and provide access to this array of String data.

Part of the functionality of the DataImporter class is the ability to import data from a file, which is assumed to take a nontrivial amount of time to initialize.

It is possible that DataImporter's data will never be used. So it makes more sense to load the data to the point when it's actually needed.

Because the data property is marked with the lazy modifier, the property is only created/initialized when the data property is first accessed. By marking this property with lazy modifier we are delaying execution of expensive operation to the first time when it's needed.

That's it! Simple as that users are now more satisfied 🎉

--

--

No responses yet