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

pyry.jahkola at iki.fi pyry.jahkola at iki.fi
Thu Apr 28 13:46:12 CDT 2016


> 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 <https://github.com/apple/swift/blob/master/stdlib/public/core/CollectionAlgorithms.swift.gyb#L329-L335> 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. Whether it indeed does that, remains unclear to me, probably not <https://github.com/apple/swift/blob/master/stdlib/public/core/Arrays.swift.gyb#L925-L930>.

— Pyry

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160428/e43d435c/attachment.html>


More information about the swift-evolution mailing list