Start a Project

Lazy Collection in Swift

Lazy Collection

According to Apple:

A collection containing the same elements as a Base collection, but on which some operations such as map and filter are implemented lazily

Lazy collections are used to compute a collection lazily i.e compute value when requested. It will helps in getting rid of intermediate array creation.

In the above playground example as you can see there are 2 same sets of operations are happing on the list. But there is one minor difference i.e on the 2nd list we are using the lazy property. It helps in reducing the computation time significantly. The lazy property is a LazySequence<T> type. The LazySequence contains the same element as the sequence. But on this, some operations such as map and filter are implemented lazily.

Lazy Property Limitation

Now as you have seen lazy property performance, let’s talk about its limitations:

Caching

The output of this is not stored in the array. Hence all these modifiers will execute for each and every request.

Don’t over optimize

Do not use lazy property every time when you use a collection. For example, if your collection contains 10 items then there is no need for you to applying lazy property. As there will be no performance gain for this case.

Thank you for reading this article. If you want to read more articles regarding iOS Development click here. And if you want to know more about lazy collection then click here.

Exit mobile version