Array <T>,ContiguousArray <T>和ArraySlice <T>之间有什么区别?在Swift中? [英] What’s the difference between Array&lt;T&gt;, ContiguousArray&lt;T&gt;, and ArraySlice&lt;T&gt; in Swift?

查看:181
本文介绍了Array <T>,ContiguousArray <T>和ArraySlice <T>之间有什么区别?在Swift中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 2中,三种数组变体之间的主要区别是什么

  • 数组
  • ContiguousArray
  • ArraySlice

有人可以用一个真实的例子来解释这一点吗?

解决方案

来自文档:

ContiguousArray:

效率等效于Array,除非T是类或@objc协议类型,在这种情况下,使用ContiguousArray可能会更高效.但是请注意,ContiguousArray不会桥接到Objective-C.有关更多详细信息,请参见ContiguousArray与之共享大多数属性的数组.

基本上,每当您将 @objc协议类型存储在数组中时,您可能需要考虑使用ContiguousArray而不是Array./p>

ArraySlice

ArraySlice始终使用连续存储,并且不桥接到Objective-C.

警告:不建议长期存储ArraySlice实例

因为ArraySlice呈现了一些更大的存储的视图 即使原始数组的生命周期结束后,也要存储该切片 可能会延长不再访问的元素的寿命, 可能表现为明显的内存和对象泄漏.阻止 这种效果,只能将ArraySlice用于瞬态计算.

当您想从数组中获取子范围时,通常会使用ArraySlices,例如:

let numbers = [1, 2, 3, 4]
let slice = numbers[Range<Int>(start: 0, end: 2)] //[1, 2]

在任何其他情况下,您都应使用Array.

In Swift 2, what is the major difference between the three array variants:

  • Array
  • ContiguousArray
  • ArraySlice

Can anyone explain this with a real world example?

解决方案

From the docs:

ContiguousArray:

Efficiency is equivalent to that of Array, unless T is a class or @objc protocol type, in which case using ContiguousArray may be more efficient. Note, however, that ContiguousArray does not bridge to Objective-C. See Array, with which ContiguousArray shares most properties, for more detail.

Basically, whenever you would store classes or @objc protocol types in an array, you might want to consider using ContiguousArray instead of an Array.

ArraySlice

ArraySlice always uses contiguous storage and does not bridge to Objective-C.

Warning: Long-term storage of ArraySlice instances is discouraged

Because a ArraySlice presents a view onto the storage of some larger array even after the original array's lifetime ends, storing the slice may prolong the lifetime of elements that are no longer accessible, which can manifest as apparent memory and object leakage. To prevent this effect, use ArraySlice only for transient computation.

ArraySlices are used most of the times when you want to get a subrange from an Array, like:

let numbers = [1, 2, 3, 4]
let slice = numbers[Range<Int>(start: 0, end: 2)] //[1, 2]

Any other cases you should use Array.

这篇关于Array <T>,ContiguousArray <T>和ArraySlice <T>之间有什么区别?在Swift中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆