Internal structure of the ContiguousArray
I know there are some related questions about the difference between Array
and ContiguousArray
.
However, the answers focus on how to use them rather than themselves.
In the official documentation they say
The ContiguousArray type is a specialized array that always stores its elements in a contiguous region of memory. This is in contrast to Array, which can store its elements in a contiguous region of memory, or in an NSArray instance if its Element type is a @objc class or protocol.
So, Array
an element can be in a contiguous scope or instance NSArray
if that element is a @objc class or protocol. I thought I Array
only has pointers to objects. So, I don't understand the meaning of the adjacent area .
And how NSArray
is it related to Array
? Is it Array
just a shell NSArray
?
Can anyone please explain?
EDIT: I had some confusion when I posted the question. Presumably ContiguousArray
doesn't have a pointer? As the document says to ContiguousArray
always keep its elements in the adjacent area.
source to share
Array
and ContiguousArray
themselves have no reference semantics. If you store instances of the value type in both elements, your array elements are appropriately copies of the original instances. Whether pointers are sometimes "under the hood" for optimization (or for moving to Objective-C) is just an implementation detail, not part of the intended programming model, and so you shouldn't just speculate about it.
But when poor performance is an issue, it ContiguousArray
is to ensure that the elements are contiguous in memory, for example in an array C. A regular Array
instance provides the same optimizations when possible (when its elements are enumerations or structures). In other cases, it can actually behave like a wrapper around NSArray
.
source to share