MemoryLayout in Swift
How big is it?
Difficulty: Beginner | Easy | Normal | Challenging
Knowing how much memory something takes up in Swift is really important. We can find that out, but we need to know something about MemoryLayout
— which is great, because that’s what this article is all about!
Prerequisites:
- Be able to produce a “Hello, World!” iOS application (guide HERE)
Terminology
alignment: the way data is arranged and accessed in memory
Byte (Octet): 8-bits
size: the number of bytes to hold a type in memory
stride: the number of bytes between two elements in memory
type: A representation of the type of data that can be processed, for example Integer or String
Memory Layout
We can find out about the memory layout of Swift types using MemoryLayout, this gives us the layout, size and stride as is relevant to the MemoryLayout and the type in question.
- The size of a type tells you how many bytes it takes to hold that type in memory.
- The stride of a type tells you how far apart each instance of the type is in memory.
- The Alignment of a…