Swift Copy on Write

288 阅读1分钟

这是我参与更文挑战的第1天,活动详情查看: 更文挑战


swift 中的类型有两种

  • value types 值类型
  • refrence types 引用类型

value type

where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple.

所有基础类型

  • struct
  • enum
  • tuple
  • Array
  • String
  • Dictionary

refrence type

where instances share a single copy of the data, and the type is usually defined as a class.

  • class

Copy on Write

Swift 将 Collections 也设计成了值类型,在将其赋值给新的变量或作为参数传入一个方法时,会在内存空间中占用大量内存。这时 Swift 使用一种写时赋值技术 copy-on-write 来解决。

给自定义值类型实现 copy-on-write

很可惜 swift 只给 Array 和 Collections 实现了 copy-on-write 但在实际场景中对于很多很大的 struct 可以自己实现 copy-on-write

final class Ref<T> {
  var val: T
  init(_ v: T) {val = v}
}

struct Box<T> {
    var ref: Ref<T>
    init(_ x: T) { ref = Ref(x) }

    var value: T {
        get { return ref.val }
        set {
          if !isKnownUniquelyReferenced(&ref) {
            ref = Ref(newValue)
            return
          }
          ref.val = newValue
        }
    }
}

相关文档

Apple Value and Reference Types

Apple Advice: Use copy-on-write semantics for large values