Member-only story
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 type is the maximal alignment of all its’ fields
A type’s stride must be greater or equal to the size of the same (as we shall see). The measurement of these is always in bytes
Size, stride and alignment for Booleans
We can create a very simple object in Swift, and that object can contain Booleans since each boolean is always one byte in Swift.
MemoryLayout<Bool>.size // 1
MemoryLayout<Bool>.stride // 1
MemoryLayout<Bool>.alignment // 1
The alignment is 1 since a Bool can start at any address, the size is 1 as a boolean is 1 byte, and it has a stride of 1 as we are only dealing with a single Bool here.
The minimal example
We can create a very simple object in Swift, and that object can contain Booleans since each boolean is always one byte in Swift.