Chameleon
Chameleon

Reputation: 1608

what happens to a "local" var after expression?

Note: "local" meaning contained with in {}

What happens to localVar after func has been expressed?

var constantVarHolder = Int()

func NameOfFunc(){
    var localVar = Int()
    if X = 0 {
        localVar = 3
    }
    else {
        localVar = 4
    }
    constantVarHolder = localVar
}

Does it become de-initialized, as in no longer using any memory or CPU?


I understand that If I changed the code to..

var singleVar = Int()

func NameOfFunc() {
    if X = 0 {
        singleVar = 3
    }
    else {
        singleVar = 4
    }
}

..would speed up the timing and memory usage for the duration the expression of func.


But after func has completed, would both codes leave your system in identical states?

Upvotes: 0

Views: 80

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

Your first example doesn't do what you expect it to do (you're shadowing localVar). But I assume you really meant this:

var constantVarHolder = Int()

func NameOfFunc(){
    var localVar = Int()
    if X = 0 {
       localVar = 3
    }
    else {
        localVar = 4
    }
    constantVarHolder = localVar
}

The short answer is that the optimizer is free to rewrite your code in ways that are logically the same, so your assertion that the second version would be faster than the first (as I've given it) is not correct. They could easily be the identical. The compiler is free to assign local variables to registers, so there may be no RAM usage at all. These variable would be stored on the stack in any case, but it really doesn't matter to this case.

Your question about "CPU" doesn't make sense in this context at all. Variables don't use CPU time. Computation does.

"leave your system in identical states" is an over-broad term. Almost certainly the state will be different in some way. But yes, the global variable will have the same value in either case (assuming you write you code as I've provided it), and all the local variables will have been freed (if they ever existed, which is unlikely).

It's really hard to imagine a case where this question is useful. Even if the optimizer doesn't remove the local stack variable, any tiny time difference of moving an immediate value to the stack and then copying from the stack to RAM is dwarfed by the cost of calling the function in the first place (assuming it isn't inlined). If you're seriously trying to speed up this function, you're looking at this in completely the wrong way.

That said, the way to answer your questions is to look at the assembly output. In Xcode, open the Assistant Editor, and select "Assembly" and then select at the bottom "Profile" or "Release" so it's optimized. If you care about this level of optimization, you'll need to get used to reading that output so you can see what code is actually running.

Upvotes: 2

Related Questions