Understanding Copy-on-Write in Swift

Tram Ho

In Swift, we have reference type (Class) and value type (Struct, Tuble, enum). The value type is essentially a copy. This means that if you assign a value type to a variable or pass it as a function parameter (not inout), the data of this value type will be copied. Now, you will have 2 value types with the same content but with 2 separate memory addresses. Today we will talk about Copy-on-Write (CoW), which is very important to understand how to manage the value type memory of Swift.

What is copy-on-write?

In Swift, when you have a large number of value types and assign or pass them across functions, copying is very costly in terms of performance because you will have to copy all the data to another location in memory. To minimize this problem, Swift’s standard library has implemented a mechanism for some type of value types such as Arrays, where values ​​are only copied when they are changed, even when there is more than one reference. to it (because if the value has a unique reference, it doesn’t need to be copied anymore, then it just needs to change over the reference). Then, if you just assign or pass an Array via the function, there will be no need to copy and will improve performance

An important note is …

Copy-on-Write is not the default way of working with value types, it is only installed for certain types of data in Swift Standard Library such as Array and Collection. This means that not every value type in the Swift Standard Library has CoW. Naturally, the value types you create yourself won’t have, unless you install them yourself (discussed later).

Now let’s see how it works through the following example:

This is a simple way to show how Copy-on-Write works. Initialize array1 with value, then assign to array2. Meanwhile, when array2 has not changed, we can see that it has never been copied, the address of array2 is still the same as array1. After changing array2, we see that its address has been changed.

Set Copy-on-Write for custom value type

You can install CoW for your value type yourself. The following example can be found in OptimizationTips.rst of Swift main repo.

This is a new piece of code that shows how to use a reference type to set CoW for any value of T type. Basically, this is a wrapper that manages the reference type and only returns a new instance when the value has no unique reference. On the other hand, it only changes the value of the reference type


Copy-on-Write is a clever way to optimize the copy of value type and is a mechanism used a lot in Swift, although it’s almost impossible to see because it’s already installed in Standard. Thư viện. But it is certainly good to know and apply it to daily code to improve the performance of the application.

Share the news now

Source : Viblo