OmniProg OmniProg - 16 days ago 6
Swift Question

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.

Rob Rob
Answer

No, data is not guaranteed to be stored in contiguous memory. If you use withUnsafeBytes or withUnsafeMutableBytes, though, it will copy it to a a location which will have the data in single contiguous block. If you don't want to incur that overhead, it's better to call enumerateBytes, which will, if the data is not currently contiguous, will call the closure for once for each of the separate blocks of memory, avoiding the overhead of copying of the full data to a new contiguous block.

Comments