5

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?

Henry Cooke
  • 2,563
  • 2
  • 23
  • 22

2 Answers2

9

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)

Community
  • 1
  • 1
Chuck
  • 234,037
  • 30
  • 302
  • 389
0

If you can reuse a variable then do it. No need to declare a new one each iteration if it's not needed.

Peter Warbo
  • 11,136
  • 14
  • 98
  • 193
  • 3
    That makes the variable have a scope larger than needed so a greater possibility of being misused – mmmmmm Jun 13 '12 at 16:54
  • 2
    I can't agree with this as stated. You should use variables in the way that makes the most sense semantically. Trying to force reuse on them is a recipe for bugs. Unless you have a real problem and the change measurably solves that problem, reducing your program's readability for speculative performance gains is almost always a bad idea IMO. – Chuck Jun 13 '12 at 17:15
  • I also agree with you @chuck for me it eases readability so whenever I can reuse a variable I do it. – Peter Warbo Jun 13 '12 at 17:40