OmniProg OmniProg - 1 year ago 117
Swift Question

Is NSData/Data storage contiguous?

Are Data/NSData bytes guaranteed to be stored in contiguous memory? Looking at the documentation (, I'm under the impression that one can access a contiguous representation of the bytes using

. 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
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download