Friday, February 26, 2016

Refactoring: Lazy initialized attribute

Apply the type of refactoring when you have a number of objects that are initialized at the beginning of the program and that take some time to be created. This is causing some delay.

Instead of initializing them at the start, do it only when they are needed.

Let's consider the following example.

We have an object called SlowClass that takes some time to be created.

class SlowClass {
    init(index:Int){
        //this takes a long time
    }
}

We also have a repository that needs 1000 instances of this object


class Repository {
    var array = [SlowClass]()
    init(){
        for i in 0...1000 {
            let slowClass = SlowClass(index: i)
            array.append(slowClass)
        }
    }
}

If the class takes 1/10 sec to be created, then our program will take 1.5 minutes to start. This is not acceptable.

We need to change the strategy and create the objects only for when they are needed.

One way of doing it is by changing the structure from an Array to a Dictionary:

class Repository {
    var dictionary = [Int:SlowClass]()
    
    func getSlowClassAt(index: Int) -> SlowClass {
        let slowClass = dictionary[index]
        if let slowClass = slowClass {
            return slowClass
        }
        let newSlowClass = SlowClass(index: index)
        return newSlowClass
        
    }
}

As you can see, when the program starts the dictionary is empty.

Only when one instance is needed and it does not exist yet, it is created.


No comments:

Post a Comment