When to declare variables and the compiler's intelligence
When to declare variables and the compiler's intelligence
- Subject: When to declare variables and the compiler's intelligence
- From: Patrick Robertson <email@hidden>
- Date: Mon, 16 Apr 2012 10:48:01 +0100
Another one on the underlying nature of the compiler and Objective-C for
you here!
I'm interested in how clever the compiler is at deciding where to create
variables etc. in the code, and whether it's more efficient (OK, it'll be
negligible) to declare variables only when they're needed for example, I
have the following method:
-(void)myMethod {
NSString *stringOne = @"hello";
NSString *stringTwo = @"goodbye";
if ([stringOne isEqualToString:@"hello"]) {
// do something
return;
}
if ([stringTwo isEqualToString:@"hello"]) {
// do something else
return;
}
return;
}
In this case, the 1st 'if' statement is true, so my method will return
before ever using stringTwo, making me think that assigning this string is
wasteful. Is the compiler aware of this, or should I declare stringTwo only
when it's needed (i.e. just before the 2nd 'if' statement)? Of course, for
ease of reading it's easier to define all vars at the start of the method,
but I'm just interested in how things work.
Thanks!
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden