Frage

I have a list of long values:

300210, 300211, 310210, 310211, ...

I'm looking for the best way to check whether a number is present in a collection. The collection is non mutable and this check can possibly happen hundreds of time per second (it's part of a physics engine collision presolving).

If using an NSArray, I'm to use NSNumbers. These are objects - Is the containsObject: method using hashcodes? Or does it consistently use a value comparison (rather than pointer address)?

How about NSSet? I know it has a member: method to use isEqual: but no practical experience with it.

thanks for your help find the best way to address this.

War es hilfreich?

Lösung

I would suggest turn on objective-C++ and use std::set. It's much faster then NSSet. You will need:

in header:

#include <set>
using namespace std;

in code:

set<int> numberCollection;

Andere Tipps

Using NSArray, if the array contains NSNumber then you can use containsObject: as they match with the value not with the pointers.

NSNumber *num3 = [NSNumber numberWithInteger:3];
NSArray *array = @[@1, @2, num3, @4, @5];

BOOL isExists = [array containsObject:@3]; // yes

Also with NSSet you can do similar way:

NSSet *set = [NSSet setWithArray:array];

BOOL isExists = [set containsObject:@3];

You can read a great article about Objective-C collections and their performance at objc.ico.

In your case (checking if a collection contains given object) the NSSet is definitely the best choice.

NSSet and its mutable variant NSMutableSet are an unordered collection of objects. Checking for existence is usually an O(1) operation, making this much faster for this use case than NSArray.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top