[swift-evolution] [Pitch] Don't require & for UnsafeRawPointer

Andrew Trick atrick at apple.com
Thu May 18 16:30:47 CDT 2017


> On May 18, 2017, at 12:38 PM, Anders Kierulf <anders at smartgo.com> wrote:
> 
>> And you don’t want to create a temp copy:
>> 
>>  var tupleMemory = letTuple
>>  get(&tupleMemory, at: 2)
>> 
>> In this case, the letTuple->UnsafeRawPointer conversion is likely going to create that copy anyway in order to give the tuple a memory address. A slightly more compelling example would be:
>> 
>> struct S {
>>  var tuple: (Int, Int, Int, Int, Int, Int)
>> }
>> 
>> func foo(s: S) -> Int {
>>  var tupleMemory = s.tuple // was s.t, should be s.tuple [AK]
>>  return get(&tupleMemory, at: 2) // fails: wrong type
>> }
>> 
>> Are you more concerned that the copy won't be optimized away or that you need the extra line of code?
> 
> My main concern is performance. In my code, the tuple is often 380 words long, so a copy completely kills performance. This part of my code is performance critical, which is why I can’t just use Swift’s standard Array type.


I agree with your proposed language changes, but there’s really a larger issue. Until we have move-only types and ‘shared’ argument conventions, I’m afraid that passing around a large struct, or even implicitly converting it to a pointer creates copies. `let` doesn’t give you a no-copy guarantee. If those copies aren’t already optimized at -O, it’s possible the optimizer could be improved to handle your cases. However, I don’t think you should rely on that. For now, until the ownership work is further along, the best way to avoid copies is to embrace mutability. Declare your large value types as `var` and always pass them `inout`.

I just noticed this bug, which has shows why the type system can make a copy impossible to avoid.
https://bugs.swift.org/browse/SR-4581 <https://bugs.swift.org/browse/SR-4581>
If you don’t care about conforming to UnsafeMutableCollection and implementing subscript { get } conformance, maybe you can avoid that problem.

Another option is to use indirect reference-counted storage for your fixed array, just like Array, so incidental copies aren’t expensive.

-Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170518/880fed58/attachment.html>


More information about the swift-evolution mailing list