• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Is checking -count worth it?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

  • Follow-Ups:
    • Re: Is checking -count worth it?
      • From: Matthew Schinckel <email@hidden>
References: 
 >Is checking -count worth it? (From: Steve Cronin <email@hidden>)

  • Prev by Date: [MEET] CocoaHeads: Silicon Valley DATE CHANGED
  • Next by Date: Re: Help on Menu Item
  • Previous by thread: Re: Is checking -count worth it?
  • Next by thread: Re: Is checking -count worth it?
  • Index(es):
    • Date
    • Thread