# Solving the mutating slice CoW problem

**URL:** <https://forums.swift.org/t/solving-the-mutating-slice-cow-problem/35297>\
**Category:** Standard Library\
**Created:** [April 11, 2020, 11:56pm UTC](https://forums.swift.org/t/solving-the-mutating-slice-cow-problem/35297 "2020-04-11T23:56:59Z")\
**Posts on this page:** 1\
**Showing post:** 35

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [April 24, 2020, 10:45pm UTC](https://forums.swift.org/t/solving-the-mutating-slice-cow-problem/35297/35 "2020-04-24T22:45:37Z")

</div>

Hi Dmitri!

> [@gribozavr](#):
>
> Could the issue be that we want `Slice` to sometimes represent a separate independent value, and sometimes a mutable borrow that passes writes through?

While that's _true_, I don't think it captures the reasons for our problem. I think what you just described is a characteristic of anything that can be written through a property or subscript. For example, here's a `String` property doing that:

```swift
struct X { var s = "abcde" }
var x: X

// `String` acts as independent value
var t = x.s
t.removeLast() // doesn't affect x

// `String` acts as “mutable borrow” that passes writes through.
x.s.removeLast()  

```

# Making it performant with CoW

When the target of the write is implemented with CoW, getting good performance depends on the property/subscript access not prematurely claiming an additional reference. **When the target is already stored in memory** somewhere, the compiler happens to oblige us by not claiming that reference, provided the accessor is either:

- `yield`ing the target's address from a `_modify`, or
- is the accessor synthesized by the compiler for regular stored properties

# The issue for slicing…

…is two^H^Hhreefold: [EDITED]

1. When you slice an array, the `Slice` instance isn't already in memory anywhere, so it has to be constructed on the stack. At least today, that construction eagerly claims an additional reference to the buffer.

2. If we could avoid claiming a reference for the `yield`ed slice, when a slice is reshaped:

3. If you could avoid claiming a reference for the yielded slice, you'd still need to prevent the array buffer from being deallocated in situations like this

---

_[View the full topic](https://forums.swift.org/t/solving-the-mutating-slice-cow-problem/35297)._
