NSArray 和 NSSet 的区别

NSArray:有序的集合,存储的元素在一个整块的内存中并按序排列(废话,我学过c语言的数组这还不知道啊);

NSSet:无序的集合,散列存储。

读developer.apple关于NSSet的解释: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.

就是说,如果搜索一个元素,NSSet的效率会比NSArray高。为什么呢?刚开始迷糊了,原来道理比较简单:hash!NSSet中元素的存储和访问都是一个hash的过程。比如你要存储元素A,一个hash算法直接就能直接找到A应该存储的位置;同样,当你要访问A时,一个hash过程就能找到A存储的位置。而对于NSArray,若想知道A到底在不在数组中,则需要一个一个元素比较,显然效率没了。Just it!

原文地址:https://www.cnblogs.com/gaoxiao228/p/2483579.html