Thursday, February 9, 2023

Copy-On-Write In Swift

 Types in Swift fall into one of two categories

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

* Reference types: each instances share a single copy of the data, and the type is usually defined as a class.

What is Copy On Write

Copy on write is a common computing technique that helps boost performance when copying structures. To give you an example, imagine an array with 1000 things inside it: if you copied that array into another variable, Swift would have to copy all 1000 elements even if the two arrays ended up being the same.

This problem is solved using copy on write: when you point two variables at the same array they both point to the same underlying data. Swift promises that structs like arrays and dictionaries are copied as values, like numbers, so having two variables point to the same data might seem to contradict that. The solution is simple but clever: if you modify the second variable, Swift takes a full copy at that point so that only the second variable is modified - the first isn't changed.

Warning: copy on write is a feature specifically added to Swift arrays and dictionaries; you don't get it for free in your own data types.

Implement Copy-on-Write for your custom value type

```

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 (!isUniquelyReferencedNonObjC(&ref)) {

            ref = Ref(newValue)

            return

          }

          ref.val = newValue

        }

    }

}

// This code was an example taken from the swift repo doc file OptimizationTips 

// Link: https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst#advice-use-copy-on-write-semantics-for-large-values

```

Summary

This subject isn’t simple but understanding it is pivotal for your advancement as an iOS designer. Copy-on-write is one of the foremost imperative dialect highlights of Swift and ought not to be underestimated.

Credit

* https://holyswift.app/copy-on-write-in-swift/

* https://viblo.asia/p/hieu-ve-copy-on-write-trong-swift-maGK7bkx5j2

No comments:

Post a Comment