[swift-evolution] mutating/non-mutating suggestion from a Rubyist

Dave Abrahams dabrahams at apple.com
Thu Apr 28 16:12:04 CDT 2016


on Thu Apr 28 2016, "pyry.jahkola--- via swift-evolution" <swift-evolution at swift.org> wrote:

>     On 28 Apr 2016, Dave Abrahams wrote:
>
>         I think I can guess what you wanted the above to mean but, mind you, the
>         in-place sort returns `()` so you wouldn't chain its result like that.
>         On the
>         other hand, the above code already works using the non-mutating `.sort()
>         ` (to be
>         known as `.sorted()` in Swift 3), and—correct me if I'm wrong—the
>         compiler
>         probably optimises the copy away using copy-on-write anyway.
>
>     No, the compiler can't automatically turn non-mutating operations into
>     in-place operations.
>
> I'm talking about `.sorted()` in particular. Its implementation is essentially
> this:
>
> var result = ContiguousArray(self) // What if `self` is not used after this
> line?
> result.sort()
> return Array(result)
>
> Depending on what `self ` is and how copy-on-write works, if `foo().sorted()`
> was called on a temporary (unique) Array returned by `foo()`, I believe the
> initialisation `ContiguousArray(self)` could be able to reuse `self._buffer`
> instead of making a copy. 

Yes, *if* `self` was a contiguous array, there will be no copy in that
line, and *if* ARC can determine that `self` is not used after `result`
is constructed, then `result` will have a unique reference to the same
buffer and `result.sort()` can avoid doing a copy before mutating the
result.

> Whether it indeed does that, remains unclear to me, probably not.

It's worth doing an experiment; it might well work.  And if it doesn't,
someone should file a bug report :-)

-- 
Dave



More information about the swift-evolution mailing list