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 11:10:47 -0700
Kyle Sluder <mailto:email@hidden> wrote (Saturday, May
8, 2010 10:47 AM -0700):
On Sat, May 8, 2010 at 10:35 AM, James Bucanek <email@hidden> wrote:
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.
My point throughout has been that -init is called so relatively
infrequently (unless you are something so basic as NSString or
NSArray) that it's not worth thinking about optimizing away a single
branch on the return value of self.
Generally, that's true.
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.
I think this falls squarely into the realm of micro-optimization. I
don't think I've ever seen -init show up in any performance profile.
I have. I have an application that creates hundreds of millions
of lightweight placeholder objects, and the code can spend 98%
of its time in +alloc/-init. Rare? Yes. Unheard of? No. Worth
trying to optimized -init? I thought so. :)
For the record, my best optimization was to cache the address of
the +alloc and -init methods (using +instanceMethodForSelector:)
and invoke the [MyClass alloc] and [super init] methods using
direct function calls. Improved performance almost 100%. Way
ugly, but worth it.
Learning about the self=[super init] tradeoffs was just a perk
of the exercise.
Computer time is cheap, programmer time is expensive. The minimal time
you save by optimizing -init will almost certainly be overridden by
the time you spend thinking about how to implement -init rather than
doing it from muscle memory. This incurs an opportunity cost of time
that could be spent optimizing parts of the program that are actually
bottlenecks. Not to mention the potential problems it introduces when
you refactor your class to not derive from NSObject.
While you're correct about the optimization itself, my point is that
you're better off investing your time elsewhere than in optimizing
-init.
Emphatic agreement on all points.
James
--
James Bucanek
_______________________________________________
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