[swift-dev] [idle] COW wrapper in 30 lines
Dave Abrahams
dabrahams at apple.com
Thu Mar 10 17:54:37 CST 2016
on Wed Mar 09 2016, Jordan Rose <swift-dev-AT-swift.org> wrote:
> Just for fun, I wrote a wrapper for COW types that don't need the flexible inline storage of ManagedBuffer. It turned
> out to be pretty straightforward, though I didn't bother with materializeForSet and thus am incurring the cost of
> many extra value copies on mutation. The major downside is having to forward all operations through, something I'm
> sure the implementers of Array and Dictionary are very used to!
>
> Disclaimer: This is not performant; don't use it in your app.
Several issues with this:
1. a performant CoW type will often *not* want to start by copying
itself when there is a mutation. A trivial example: when you clear
an Array. So a simpleminded “always make a copy when I write the
value” approach is not going to scale.
2. The thing in your box has to be a value type for this to work. It's
pretty uncommon that a thing that's already a value type benefits
from being CoW-ified in this way. That could usually only happen
when it is quite atypically large. It's a fine optimization to make
when you can use it, but it doesn't change the programming model.
The more interesting case for CoW is to produce value semantics where
you otherwise wouldn't have it (e.g. Array).
--
-Dave
More information about the swift-dev
mailing list