On Apr 16, 2012, at 11:48 AM, Patrick Robertson wrote:
> 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)?
The compiler can possibly reorder the statements when it optimizes the code and
when the original logic is maintained. In this case, I'm pretty sure it will.
> Of course, for ease of reading it's easier to define all vars at the start of
> the method,
Personally, I do not favor this "ancient C" style. In fact, it makes code less
readable.
Rather, I define the variables immediately before they will be used.
You could even write:
if ([@"hello" isEqualToString:blah]) {
...
}
Regards
Andreas
_______________________________________________
Cocoa-dev mailing list ([email protected])
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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]