tags:

views:

744

answers:

4

when releasing an instance that could exist or not, I usually write this:

if (object != nil) [object release];

but since sending a message to nil is not a problem, is that conditional necessary?

I suppose the question comes down to this: which uses more overhead, comparing an object to nil, or sending nil a message?

+2  A: 

That check is not necessary. Unless you're doing a LOT of iterations of this code (10,000s, maybe more), the time differential is insignificant.

Ben Gottlieb
And even then, you should use a profiler before doing any optimization.
J. Pablo Fernández
+7  A: 

See this page which explains that passing messages to nil (to generalize your example) is perfectly fine.

As to what has more overhead, any performance impact will be negligible to the overall performance of the system (don't get into the habit of premature optimization).

shek
+2  A: 

When I was coding more C++ than Obj-C, I would always write code to check for nil -- because it was a note to myself that this pointer is allowed to be nil. Now, I let objc_msgSend deal with it, since I've grown more comfortable reading the code with the assumption that any pointer could validly be nil.

On a "safe coding" level, I think that it's more important to always set your pointers to nil after each release (possibly exluding a release in the dealloc method). This way, you ensure that your pointer is never invalid (it is either valid, or nil).

Matt Gallagher
+2  A: 

Obj-C checks for nil, so there's no need to do it twice.

[object release]; object = nil;

If you want add some extra code there, it's much better to set the pointer to nil afterwards, so it would be immune to double-free.

porneL