Reputation: 1274
In swift 3, i have used MemoryLayout to get the size of String Struct. The result depend on system architecture: 12bytes with 32bits OS and 24bytes with 64bits OS.
With the fixed size, how can it storage string with any size? (keep in mind that String is Struct type) and what makes the difference in size of String between system architectures?
Upvotes: 1
Views: 282
Reputation:
If you want to learn about the internals of String
then you can look directly at the source code
It boils down to the internals for the struct
which contain another struct
called _SwiftCore
. This, in turn, has a raw pointer to memory that actually stores the data for the String
. Because of this design all the struct
needs to store is a pointer and some other data about the storage and therefore the size of the struct
is not the true size of the stored data. You'd have to track down the raw storage in order to figure out the actual size of the entire String
.
Most of this is immaterial to everyday use of String
, it's an implementation detail and not necessary to understand how to use it. In fact the implementation could be done in a number of ways and still work mostly the same. Do not depend on any of these internal details, instead rely on the public-facing interfaces and documentation. The implementation could change radically from version to version, infrastructure to infrastructure so depending on it could cause major headaches down the road.
Upvotes: 2