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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With