Does Data copy-on-write?

Data is a CoW type. If a mutation is made and there are other references (i.e. it is not uniquely referenced) it will cause a copy of the underlying buffer to make the mutation. if it is uniquely referenced it will not impose a copy.

The CoW part is open sourced, look for the isUniquelyReferenced call in Data.swift (both for the swift-corelibs-foundation and the Foundation overlay).

There is one caveat to all of this: small Data payloads are always copy. If it is on a platform that the payload is less than a specified amount it will have the entire payload in stack allocation space. So for example a Data of two bytes is always on the stack and so therefore always copied when a mutation occurs, because it copies that stack memory (similar to how smol Strings work).

The tl;dr yes it is a CoW type in very similar spirit to String.

4 Likes