charlslvn
charlslvn

Reputation: 77

Use of self in Swift and performance

In terms of performance, is it better to define the let variables before building functions and then call those variables with self. ? Or is it better to define variables directly in the functions ?

 //Example 1 : 

  var firstVar:String = ""

    func fetch1(){

    let currency = "¥"

    self.firstVar = "100\(currency)"

    print(self.firstVar)

    }

//Example 2 

func fetch2(){

    let currency = "¥"
    let firstVar = "100\(currency)"

    print(firstVar)

}

Which Example performs the best in terms of performance ?

Thank you in advance

Upvotes: 1

Views: 83

Answers (1)

inexcitus
inexcitus

Reputation: 2639

I think this decision should not be about performance, but more about a question of scope. I would only declare global variables if it is absolutely necessary (i.e. you performed a complicated calculation and want to store the result for later reuse). If you only store information for a short period of time and a local variable will do the job, then I would avoid declaring global variables.

Upvotes: 1

Related Questions