Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring a variable outside a loop in Objective-C have any optimising effect?

I have acquired the habit of declaring reused variables outside loops from having worked in Other Languages, like so:

NSString *lcword;
for( NSString *word in tokens )
{
    lcword = [ word lowercaseString ];
    ...    
}

Is it reasonable to do this in Objective-C also, or is the compiler smart enough to make it unnecessary?

like image 495
Henry Cooke Avatar asked Jun 13 '12 16:06

Henry Cooke


1 Answers

There's no benefit in Objective-C that I know of. AFAIK every modern Objective-C compiler allocates the stack space for local variables at the beginning of the function or method. Scoping the variable to the loop just prevents you from using the name outside the loop and prevents the compiler from reusing the stack space if it wants to.

See also: Is there any overhead to declaring a variable within a loop? (C++) (It's about a different language, so I wouldn't mark it as a dupe, but the compiler techniques at work are very similar)

like image 78
Chuck Avatar answered Nov 14 '22 22:11

Chuck