Hacking the iOS Interview

Swift — Copy-On-Write Optimization

Shivam Pandey
Hash Coding
Published in
4 min readFeb 22, 2021

--

Swift — Copy-On-Write Optimization
Photo by Andrew Neel on Unsplash

This concept can be asked as a follow-up question when discussing structs vs classes in Swift. If you haven’t gone through my previous posts on Structs and Classes, you can find them here: Part I and Part II.

What is Copy-on-Write Optimization in Swift?

As we know that value types can only have a single owner, therefore they need to be copied every time they are passed around. When we have a value type containing a lot of data, copying them each time (even when passing around) can lead to a lot of memory consumption. To mitigate this downside, the Swift compiler adds an optimization called copy-on-write.

Using copy-on-write, the compiler does not go on creating copies of the objects when they are merely being passed around among multiple variables, unless and until a variable tries to modify the data.

Write some code to explain Copy on Write using an example

Swift arrays implement copy-on-write optimization, which means if we create an array and simply assign it to another variable (without any of the variables modifying the array), both the arrays will share the same reference to the underlying data.

Copy on Write in Swift
Code example depicting copy-on-write in Swift

In the above example, we can see in the logs printed in the console that the memory address of both the arrays — arr1 and arr2 are the same.

Now when arr2 modifies the contents of the array, its memory address is updated and the memory address of arr1 remains the same as the previous one.

Copy on Write in action in Swift
Address of arr2 has changed after modifying the array

Is there any disadvantage of Copy on Write?

Since value types can only have a single owner, they don't have to incur the overhead of reference counting. But, the Copy on Write value types needs to internally maintain a reference count to be aware of the number of copies being created of that value. When a new copy is created, the internal reference count is also incremented.

Updating the reference count is a slow operation because it has to be thread-safe, and to achieve that, locking mechanisms are implemented internally, which have their own costs. Thus, if we are not careful, the performance can be adversely affected.

Let's consider the below-given sample code containing a struct called MediaItem which contains a string, a dictionary, and an array.

When passing this MediaItem’s objects around, the internal reference count of all the properties have to be maintained. This overhead will result in a decrease in performance.

How to implement Copy on Write for custom value types?

Following up on the above example of the MediaItem struct, we can make some changes in the code to reduce the overhead.

We can wrap the properties inside a private MediaData class as shown in the example below:

By wrapping the properties inside a class, the struct now has to maintain a single internal reference count when making a copy.

We can add new computed properties to expose name and data, and can be achieved using the below approach:

Using the above implementation we can achieve Copy-on-Write for our custom value types.

We have used a not-so-commonly-used method here of the Swift Standard Library:

isKnownUniquelyReferenced(_:)
Returns a Boolean value indicating whether the given object is known to have a single strong reference.

This method is used to efficiently check the Copy on Write implementation, as we need to know if the object has a single owner. If it doesn’t, we create a copy of the object before modifying it.

I hope you find this story helpful. If you enjoyed it, share this with your community, and feel free to hit the clap button below 👏 to help others find it! Thanks for reading. 👍

Get notified every time we post a new story to our publication. Follow us now

We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. Signup Now. ✉️

--

--

Shivam Pandey
Hash Coding

Lead Engineer iOS @airtelxlabs | Editor: Hash Coding