When is it better to use an NSSet over an NSArray?

前端 未结 11 1553
-上瘾入骨i
-上瘾入骨i 2020-12-12 10:27

I have used NSSets many times in my apps, but I have never created one myself.

When is it better to use an NSSet as opposed to an NSArray and why?

11条回答
  •  有刺的猬
    2020-12-12 10:49

    Here you can find a pretty thorough comparison of the NSArray and NSSet datastructures.

    Short conclusions:

    Yes, NSArray is faster than NSSet for simply holding and iterating. As little as 50% faster for constructing and as much as 500% faster for iterating. Lesson: if you only need to iterate contents, don't use an NSSet.

    Of course, if you need to test for inclusion, work hard to avoid NSArray. Even if you need both iteration and inclusion testing, you should probably still choose an NSSet. If you need to keep your collection ordered and also test for inclusion, then you should consider keeping two collections (an NSArray and an NSSet), each containing the same objects.

    NSDictionary is slower to construct than NSMapTable — since it needs to copy the key data. It makes up for this by being faster to lookup. Of course, the two have different capabilities so most of the time, this determination should be made on other factors.

提交回复
热议问题