title: Understanding the performance of data copying in unsafe swift
body: <p>I'm finally familiar enough with Unsafe…Pointer types in Swift to try to address how the following code was marked as unsafe by XCode.</p>
  <pre><code>let pixelBuffer = UnsafeMutablePointer&lt;UInt32&gt;(&amp;pixels)
  let bytes = UnsafeRawPointer(pixelBuffer).assumingMemoryBound(to: UInt8.self)
  destination.assign(from: bytes, count: pixels.count * 4)
  </code></pre>
  <p>This generated the warning &quot;Initialization of 'UnsafeMutablePointer' results in a dangling pointer&quot;. It also runs without error and in approximately 0.00056 seconds. I've found two potential solutions, but both run slower</p>
  <p>For the sake of clarity:</p>
  <pre><code>var pixels: [UInt32] = …
  let destination: UnsafeMutablePointer&lt;UInt8&gt; = …
  let destinationCount = pixels.count * 4
  </code></pre>
  <p>I've come up with two alternatives, both of which are considerably slower. This executes in 0.00364 seconds. As I understand the documentation, Data(buffer:) performs a copy, meaning this copies twice:</p>
  <pre><code>pixels.withUnsafeMutableBufferPointer { pixelBuffer in
      let data = Data(buffer: pixelBuffer)
      data.copyBytes(to: destination, count: destinationCount)
  }
  </code></pre>
  <p>This executes in 0.02529 seconds.</p>
  <pre><code>pixels.withUnsafeBytes { pixelBytes in
      let pointer = UnsafeMutableRawBufferPointer(start: destination, count: destinationCount)
      pointer.copyBytes(from: pixelBytes)
  }
  </code></pre>
  <p>I would have suspected that due to less copying, the second solution would be faster but clearly it's not. Overall this is all negligible but I really want to understand what's going on here, and why a two-copy solution executes in 1/7 the time.</p>
  <p>For benchmarking I'm taking the interval between to Date() objects from directly before and after the block is executed.</p>