Re: self = [super init], nil?
Re: self = [super init], nil?
- Subject: Re: self = [super init], nil?
- From: James Bucanek <email@hidden>
- Date: Sat, 8 May 2010 10:35:04 -0700
Kyle Sluder <mailto:email@hidden> wrote (Saturday, May
8, 2010 8:48 AM -0700):
It might produce less code, it might not. If you're operating at the ObjC
level of abstraction and worrying about the codegen of self=[super init], your
priorities are out of order.
I'm a coding genius. My priorities are never out of order. ;)
There are completely legitimate reasons to want to optimize
one's code, and examining the overhead of -init seems perfectly
rational to me. This seemed to be the brunt of the original
poster's question.
I was simply pointing out the fallacy of believing that if
((self=[super init])!=nil) is inherently less efficient (e.g.
produces more code) than if ([super init]!=nil).
This gets back to the two mantras of optimization: Don't
optimize unless you need to. When you do optimize, do so by
measuring your baseline, change your code, measure again, and
compare the results. In other words, don't guess or assume that
something will make things faster; prove it. When this question
came up a few years ago (and it seems to come up again ever few
months), I did just that. I compiled and benchmarked code using
self=[super init] and just [super init], and the former was
shorter and faster.
So if one was to trying to improve the efficiency of their code
by breaking with the standard -init pattern, I would point out
that they would, in fact, be accomplishing the exact opposite.
The compiler can save the instructions needed to preserve
|self| before calling [super init] and restoring it
afterwards. Anyway, I've disassembled this on several
architectures and the code produced by the preferred pattern
is shorter, and therefor more efficient, than trying to take a shortcut.
Since you'd better be assigning self anyway, self doesn't need to be preserved past the call to [super init].
Exactly. Modern versions of GCC realize that you are assigning
the result of the method invocation to self, and it can
therefore safely ignore the current value of self. This ends the
lifeline of the register containing self, which means that it
doesn't need to preserve it before sending the -init message,
thus saving a few instructions.
James Bucanek
____________________________________________________________________
Author of Professional Xcode 3 ISBN: 9780470525227
<http://www.proxcode3.com/>
and Learn Objective-C for Java Developers ISBN: 9781430223696
<http://objectivec4java.com/>
_______________________________________________
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