今天阅读了一篇文章 “Collection Data Structures in Swift”
文中对swift的3种数据结构Array,Set,Dictionary做了深入探讨了实际开发中的最优选择
第一部分Array:
An NSArray is heterogeneous, meaning it can contain Cocoa objects of different types. Swift arrays are homogeneous, meaning that each Array is guaranteed to contain only one type of object.
当确定存储类型的时候,使用swift的data structures
当不确定存储类型的时候,使用NS开头的data structures(NSArray,NSDictionary)
However, you can still define a single Swift Array so it stores various types of Cocoa objects by specifying that the one type is AnyObject, since every Cocoa type is also a subtype of this.
文章中有例子,可以跑一下,这里只给出结论
swift的Array速度比NSMutableArray的读写操作快了许多,大约为10倍左右,啊呀妈呀!!
Dictionary在swift2.1 下的表现
In raw time, creating Swift dictionaries is faster than creating NSMutableDictionaries but both degrade at roughly the same O(n) rate.
Adding items to Swift dictionaries is roughly 10 times faster than adding them to NSMutableDictionaries in raw time, and both degrade close to the best-case-scenario O(1) rate promised by Apple’s documentation.
Removing items from Swift dictionaries is roughly as fast as removing items from NSMutableDictionaries, but the degradation of performance is again close to O(1) for both types.
Both Swift and Foundation dictionaries are able to lookup at roughly an O(1) rate. Like Swift arrays, dictionaries are faster in raw time than Foundation dictionaries, though the performance is very, very close.
总的来说也swift的dictionary也比NSDictionary速度快很多,建议使用
最后是Set
- set中插入同一个元素,原来的会被覆盖,所以操作set对象,会遍历整个set
- 因为set中每一个item都是唯一的,所以创建的速度比array慢
- 其他方面,set与NSSet表现几乎一样
作者还介绍了几个不常用的数据结构(data Structures)
NSCache
这个因为做图片缓存所以接触过,文中提到当内存过低时,cache会自动改变(mutate)自己,删除一些内部的对象(object),实际使用中,也遇到了,而且这货几乎很容易就内mutate 自己,几十m之后几乎就顶不住了~
NSCountedSet,NSOrderedSet
NSCountedSet 计算某一个item被加进去几次
NSOrderedSet 其实只有当要添加不重复的有序item的,才会比array效率高
NSHashTable,NSMapTable
NSHashTable不但能存储object,还能存储non-object以及其它structures
NSMapTable is a dictionary-like data structure, but with similar behaviors to NSHashTable when it comes to memory management.
NSIndexSet
用来存放index的,所以只能放**unique unsigned integers
**
这几个特殊存储结构文中都大概提了一下,等以后慢慢研究
结束:
文章最后提到了几个reference,可以看一下,更深入地探讨了一些使用上的问题