• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
When to declare variables and the compiler's intelligence
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

  • Follow-Ups:
    • Re: When to declare variables and the compiler's intelligence
      • From: Andreas Grosam <email@hidden>
  • Prev by Date: Fast Enumeration and temporary objects/autoreleasing
  • Next by Date: Re: Fast Enumeration and temporary objects/autoreleasing
  • Previous by thread: Re: Fast Enumeration and temporary objects/autoreleasing
  • Next by thread: Re: When to declare variables and the compiler's intelligence
  • Index(es):
    • Date
    • Thread