NSArray Vs NSSet

I know NSSset is used for unique collection when NSArray can contains dusplicate object. Which one is preferred from time and space complexitiy standpoint? Is NSSet faster than NSArray as it is unordered collection?

Replies

From

https://developer.apple.com/documentation/foundation/nsset?language=objc

"You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower than with sets.


This refers to the method "containsObject:"

Got it. Thanks. I think the array is faster in other ways and preferred if the developer is not going the check whether the object is present in the given array.

Which one is preferred from time and space complexitiy standpoint?

That depends on your access pattern. Sets can insert and remove elements in O(1), assuming your hash value is sound. Arrays can add and remove elements at the end in O(1), but inserting and removing elements in the middle is O(n), where n is the size of the array.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"