Re: Is checking -count worth it?
Re: Is checking -count worth it?
- Subject: Re: Is checking -count worth it?
- From: Jens Alfke <email@hidden>
- Date: Wed, 23 Jul 2008 23:42:44 -0700
On 23 Jul '08, at 9:15 PM, Steve Cronin wrote:
Is this code worth it?
if ([M count]>0) [M removeObject:O];
OR should I just do
[M remove O];
No, the first line is not worth it. You've added an extra message-send
(which is _not_ cheap) to pre-check something that the NSArray (really
CFArray) implementation is going to implicitly check anyway. You've
also made your code harder to read, and slightly larger.
If you really want to make that particular line of code faster, here's
a tip: If you know O is the exact object in the array (not just that
it's equal to an object in the array), it's considerably faster to
call -removeObjectIdenticalTo: instead of -removeObject:, because it
avoids having to call -isEqual: on every object in the array. While
this is not a good idea for arrays of "value objects" like NSStrings
or NSDatas, it's useful with classes where two different instances
will never be isEqual: to one another (for example NSViews.)
An even better optimization, if you don't care about the order of the
objects, is to use a set instead of an array. Removing an object from
a large set is much, much faster than removing from a comparable
array. (For NSSet it's O(1) while for NSArray it's O(n).)
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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