Copy on Write

Ahmet Giray Uçar
2 min readMar 20, 2023

Swift is an amazing language. Not only it’s developer friendly, easy to understand syntax, it has lots of features like automatic memory management, named parameters, extensions, performance optimizations and many more. We will take a look at one of the Swift’s performance optimization. Let’s start.

What is it?

“Copy on Write” is a memory management technique that can be used to optimize the performance of value types in Swift. Remember that this optimization is only made for the value types and it’s not the default behavior of value types, it is implemented on some certain types such as Array and Dictionaries. Also, the value types that you create doesn’t have it, unless you implement it yourself. We will explore how to implement it for the custom types.

It is a strategy that delays copying the object’s data until it is actually modified. The basic idea is that when an object is created and when a copy of the object is needed, instead of immediately copying the object’s data, the data is shared and both objects are referring to the same memory location which they act like reference types. When the object’s data is modified, a new copy of the data is created. The new copy is then modified.

In the second line, array2 is assigned to array1 and as you know, value types creates a copy the values that object owns and assigns it to new object. But it is not efficient if you are not willing to change any value afterwards. Therefore Swift team has developed this feature and data is not copied until some modifications are made to it. They act like reference types until modifications are made.

Custom Values

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)
ref.val = newValue
// This code was an example taken from the swift repo doc file OptimizationTips
// Link:

Box is basically a wrapper that manages the reference type and just returns a new instance if the value is not uniquely referenced. Otherwise, it just mutates the value of the reference type.

I hope you learnt something from the article. If you have any questions or suggestions, please contact me. Thank you for your time.

My Personal Website | GitHub | LinkedIn | Instagram | Twitter