small medium large xlarge

17 Jan 2009, 10:13
Ian (6 posts)


Thanks for the great screencast, I’m just about at the end of the first one and although I may be jumping the gun a bit I have a question which could be fundamental about my future practices regarding efficient code.

The question is straightforward, please could you tell me which of the following (if any) is more efficient and why:

// A -(NSString *)description { NSString *oldDescription = [super description]; return [NSString stringWithFormat:@”%@ title = %@, rating = %d”, oldDescription, self.title, self.rating]; }

//B -(NSString *)description { return [NSString stringWithFormat:@”%@ title = %@, rating = %d”, [super description], self.title, self.rating]; }

I am guessing that if I send a message only once then B would be more efficient because I am using less memory but if I need to send a message multiple times it’s best to option A.

Many thanks, Ian

17 Jan 2009, 11:34
Bill Dudney (917 posts)

Hi Ian,

Assuming that the first ‘%’ in the format strings should be ‘%@’ and the second description implementation has ‘self’ as the first argument these implementations will actually almost exactly the same performance profile.

In other words;

~~~ // A -(NSString *)description { NSString *oldDescription = [super description]; return [NSString stringWithFormat:"%@ title = %@, rating = %d”, oldDescription, self.title, self.rating]; } ~~~

~~~ // B -(NSString *)description { return [NSString stringWithFormat:"%@ title = %@, rating = %d”, self, self.title, self.rating]; } ~~~

Implementations A and B both call description, but B will do it automatically. All strings are autoreleased.

Its important to keep in mind Knuth’s axiom ‘premature optimization is the root of all evil’. So assuming you are wondering because you want to learn I hope this helped.

If you are really trying to optimize you should use Instruments to figure out where the real bottlenecks in your code and then optimize those spots.

Good luck.

You must be logged in to comment