shle2821 shle2821 - 6 months ago 39
Swift Question

Lazy Initialization sounds and works great. Why not always default to using lazy initialization?

Seems like lazy initialization is great. I understand the concept and have tested on my code and I don't see any lags. Then the question is, why not always use lazy initialization? What's the drawback to this? What am I not being aware of?

Answer Source

Consider this example of a lazy var:

struct S {
    lazy var lazyVar: Int = { /* compute some value */ 0 }()

What really happens behind the scenes is something like this:

struct S {
    var _lazyVar: Int? = nil

    var lazyVar: Int {
        mutating get {
            if let existingValue = _lazyVar {
                return existingValue
            else {
                let newlyComputedValue = /* compute some value */ 0
                _lazyVar = newlyComputedValue
                return newlyComputedValue

As you see, every access of lazyVar requires a branch, to check if there's a value already, or if it's necessary to compute one for the first time. This adds overhead that easily outweighs the benefit of lazily evaluating values with simple (fast) derivations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download