ArraySlice instances share memory?

I'm trying to understand some documentation. So ArraySlice just points to the same memory as its source Array, right? The slice just basically stores a pointer and a range. Wouldn't this mean that returning separate segments of an array as multiple slices could be more memory-efficient (than copying them to new top-level collections)?

That it does.

It depends on the size of original array, and the slices.
If there are multiple slices, each take a large portion of array, there may be some memory benefit.
If each slice is very small, but the original array is huge, it may be better to copy data onto new arrays and let the original be deallocated.

And to again mention that slice is not appropriate for long term storage as it prevents the original data from being deallocated (see warning in the doc)

1 Like

Right. More specifically, it stores a "copy" of the original array, but Array has copy-on-write semantics, so as long as neither the original nor the copy is mutated, they'll share the same storage.

It depends—if the slices cover most of the array, and especially if they overlap, it probably saves memory; if the slices cover only a tiny portion of a large array, it probably wastes memory. As a user of the type, you need to figure out which one is more likely to apply in your code.

1 Like