Search code examples
swiftnsdata

Is NSData/Data storage contiguous?


Are Data/NSData bytes guaranteed to be stored in contiguous memory? Looking at the documentation (https://developer.apple.com/reference/foundation/data), I'm under the impression that one can access a contiguous representation of the bytes using withUnsafeBytes() or withUnsafeMutableBytes(). However, it is possible that the bytes are copied from non-contiguous storage to a contiguous block when these methods are invoked.

I think it would be somewhat inefficient to copy the bytes when accessing them via those withUnsafe... methods, and the bytes are evidently stored contiguously when the init(bytesNoCopy: ...) initializer is used, so I tend to think that they are always stored contiguously, but haven't seen any docs stating so explicitly.


Solution

  • No, Data is not guaranteed to be stored in contiguous memory. If you use withUnsafeBytes or withUnsafeMutableBytes, though, it will copy all the buffers to a single contiguous buffer.

    If you do not want to incur that overhead, you can access the individual buffers using the regions property.