[swift-evolution] Improved value and move semantics
Karl
razielim at gmail.com
Fri Jul 29 23:45:50 CDT 2016
> On 29 Jul 2016, at 18:42, Bram Beernink via swift-evolution <swift-evolution at swift.org> wrote:
>
> Hi all,
>
> Would it be possible to improve value and move semantics (performance) in Swift? Consider this possible Swift code in a future release of Swift:
>
> let array1 : [String] = ["Val1", "Val2"]
> let array2 = array1.appended(“Val3”) // Copy of array1 with “Val3” appended. array1 is left untouched. Nothing special yet.
> var array3 : [String] = [“Var1”]
> array3 = array3.appended(“Var2”) // array3 can just be mutated to add “Var2”, while maintaining value semantics. Swift can recognize that array3’s old state is not referenced anywhere in the future.
> let array4 = array2.appended("Val4").appended("Val5") // Copy of array2 with both "Val4" and "Val5" appended. In this case, “Val5” can also be appended by mutation.
>
> This example illustrates improved value semantics with a string array. But it would be good if this can work with any struct. Maybe via something similar to isUniquelyReferenced? Or maybe you can even have a “smart” self in a non-mutating func in a struct:
> struct Array<T> {
> func appended(e : T) -> Array<T> { // No mutating keyword!
> self.append(e) // self would either be mutated here if the current ref count of self is 1, and self is either a “rvalue” or self’s old state cannot possibly referenced anymore after this call. Otherwise, "self” would actually be a copy of self.
> return self
> }
> }
>
> I think that with such support it is encouraged to make more use of (immutable) value types while not sacrificing performance. Less mutations lead to more understandable code, which leads to less bugs.
>
> In any case, keep up the fast improvements to Swift.
>
> Best regards,
> Bram.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
It’s a known issue. See: https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst#advice-use-inplace-mutation-instead-of-object-reassignment <https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst#advice-use-inplace-mutation-instead-of-object-reassignment>
I’m not a compiler expert, but in theory I’d expect a smart-enough, fast-enough optimiser to be able to replace those with mutating calls.
Karl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160730/8257165d/attachment.html>
More information about the swift-evolution
mailing list