Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 146 ยท Advanced Swift

Memory Layout

Understand how Swift stores values: MemoryLayout size, stride and alignment, struct padding, optionals and enums, class references and raw bytes.

Most of the time you do not need to know how Swift lays out your values in memory, and that is a feature. But sooner or later a question comes up: why is this struct 24 bytes when its fields add up to 10? Why is Int? bigger than Int, while Bool? is not? How big is a String really? Is it worth reordering fields? Knowing the answers lets you predict performance, talk to C libraries, read binary formats and understand what the unsafe APIs in the next lesson are really doing.

Swift gives you a single tool for these questions: the generic type MemoryLayout<T>. It reports three numbers for any type, and this lesson explains what they mean and why they differ. All sizes below were measured on the site's runner: Swift 6.3 on 64-bit Linux (x86-64). On other 64-bit platforms they are almost always identical; on 32-bit systems pointers and Int are 4 bytes instead of 8.

Layout is mostly an implementation detail. Swift does not promise a layout for its own types unless they are marked @frozen or imported from C, and it can improve layouts in future versions. Measure, understand, but never write code that depends on an exact number for a Swift-native type.

Size, stride and alignment

There are three numbers:

  • size: the number of bytes the value itself needs.
  • alignment: the value must start at an address that is a multiple of this number. A 4-byte Int32 wants an address divisible by 4, an 8-byte Int wants one divisible by 8. CPUs read aligned data faster, and some cannot read misaligned data at all.
  • stride: the distance in bytes between the start of one element and the start of the next in an array. It is the size rounded up to the next multiple of the alignment.

Use stride, not size, when you compute the memory an array of values needs. Here is a small helper that prints all three for any type:

Swift size, stride and alignment of common types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The integers are what you expect: Int8 is 1 byte, Int32 4, and Int is 8 bytes on a 64-bit system. Bool takes a whole byte. Character and String are both 16 bytes, Array is only 8, UUID is 16 bytes with alignment 1 (it is a tuple of 16 bytes), a Range<Int> is two Ints (16), a closure is 16 (a function pointer plus a context pointer), and Any is 32. Void, the empty tuple, has size 0 and stride 1: a value that carries no information needs no bytes, yet an array of them still gets distinct positions.

Some entries need explanation. Why is an Array 8 bytes, whatever it holds? And why is a String only 16? That is the next topic.

Value types and the references inside them

MemoryLayout<T>.size measures the value you store in a variable, not everything it points to. An array variable is one pointer to a heap buffer that holds the elements, the count and the capacity. A class instance variable is one pointer too:

Swift What the variable holds versus what it points to

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The class reference and the array variable are both 8 bytes, the size of one pointer, no matter how big the Document is. size(ofValue:) gives the same answer as the type-based call, 8; the three integers in the array's buffer take 24 bytes more, somewhere on the heap. A String is always 16 bytes. Swift stores small strings of up to 15 UTF-8 bytes directly inside those 16 bytes, with no heap allocation at all, which is why "Swift" is cheap to create and copy. A longer string keeps a pointer and a length instead, and its text lives in a separate buffer. Both look the same through MemoryLayout: it measures the container, not the characters.

This is also the answer to a classic interview question: copying an Array or String variable copies 8 or 16 bytes plus, at most, a reference-count increment. The elements are only copied when one of the copies is mutated (copy-on-write; see Value vs reference types).

Padding and field order

A struct's fields are placed in the order you declare them, each at the next address that satisfies its alignment. Space left between fields to satisfy alignment is called padding. The struct's alignment is the largest alignment of its fields, and its stride is its size rounded up to that alignment, so there is also padding at the end. Compare two structs with the same three fields in a different order:

Swift Padding depends on the order of fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Scattered has its flag at offset 0, then 7 bytes of padding so that big can start at offset 8, then other at offset 16: size 17, stride 24. Packed puts big at 0, then the two booleans at 8 and 9: size 10, stride 16. The same data takes 24,000 bytes in a thousand-element array one way and 16,000 the other. MemoryLayout<T>.offset(of:) takes a key path and tells you exactly where a stored property lives; it returns nil for properties that are not stored directly, such as computed ones.

A simple rule gets you most of the benefit: declare fields from largest alignment to smallest. It is a cheap change that helps when you keep millions of small structs in an array. It is not worth contorting a struct's design for a few bytes; readability first, unless a profiler tells you otherwise.

Swift does not reorder fields for you: unlike some languages, a struct's stored properties keep the declared order, which is part of why C interop works without conversion. Tuples behave the same way, as (Int8, Int64) (size 16) and (Int64, Int8) (size 9, stride 16) show when you measure them.

Optionals and enums

An optional is an enum with two cases, none and some(Wrapped), and the compiler stores it as compactly as it can. When the wrapped type has spare bit patterns that never occur in valid values, nil uses one of them and costs nothing. Otherwise an extra tag byte is needed:

Swift The cost of Optional and enums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Int? is 9 bytes with stride 16: all 64 bits of an Int are valid values, so there is no spare pattern and Swift adds one tag byte. An Int8? is 2 bytes for the same reason. A Bool? stays at 1 byte because a Bool only uses the values 0 and 1, leaving room for a third value, nil. A class reference (Node?) and a String? are no bigger than the non-optional (8 and 16), because null pointers and unused bits are available. This is why optional class references are free.

For enums, the rule is: without payloads, the tag needs just enough bits for the case count (Direction: 1 byte, Unit with a single case: 0 bytes). With payloads, the enum is as big as its largest payload plus a tag if necessary (Shape: Double payload plus a tag gives 9 bytes, stride 16). Token is 16: the String has spare bits for the extra end case. The rawValue of an enum (Status: UInt8) is not stored; the layout depends only on the number of cases, not on the raw values.

Existentials are bigger than you think

A variable of a protocol type (any Shape) is an existential container: it must hold any conforming value, so it contains inline storage for small values (three words), a pointer to type information and a pointer to the protocol's witness table. Any is 32 bytes in the first example and a protocol with methods, written any P, is 40. A generic function or some P stores the concrete type directly and avoids that overhead; see Opaque types and Performance tips.

Looking at the bytes

You can inspect the actual bytes of a value with withUnsafeBytes(of:). That is where endianness becomes visible: Swift on x86-64 and Arm is little-endian, so the least significant byte comes first:

Swift Raw bytes and endianness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints [4, 3, 2, 1]. The two forms of 0xABCD print cdab (byte-swapped) and abcd on this little-endian machine. 1.5 as a Float has the IEEE 754 bit pattern 3fc00000. Pixel is exactly 4 bytes with stride 4, and its bytes print [255, 128, 0, 255]. Always use .bigEndian / .littleEndian when you read or write files and network protocols, so your code works on every platform; the full story is in Data and Bytes.

Padding bytes have no defined value. If you dump a struct such as Scattered with withUnsafeBytes, the padding bytes contain whatever happened to be in memory, so never hash, compare or write them out. Convert fields one at a time instead.

Pointers: a first look

MemoryLayout is the vocabulary of Swift's unsafe pointer types, which are covered in Unsafe Swift. In short:

  • UnsafePointer<T> and UnsafeMutablePointer<T> point to one or more values of type T; moving to the next one adds MemoryLayout<T>.stride bytes.
  • UnsafeRawPointer points to untyped bytes; you ask it to load(as:) or storeBytes(of:as:), and you are responsible for alignment.
  • The Buffer variants add a count and conform to Collection.

Allocating raw memory shows size and alignment working together:

Swift Allocating and reading raw memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see true, 1122334455667788, 136 (the byte 0x88, because the machine is little-endian) and 2571 (which is 0x0A0B). load(as:) requires an aligned address; for a read at an arbitrary offset use loadUnaligned. storeBytes has no such restriction in current Swift.

Bit-casting between types of different sizes is where layout knowledge is most important. unsafeBitCast reinterprets the bits of a value as another type, and it insists that both have the same size:

Swift unsafeBitCast with mismatched sizes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This compiles, then stops at run time with Illegal instruction and a backtrace, and no message: the check fails because 1 byte is not 4. In this optimized build traps carry no text, so you must know what you did. Almost every use of unsafeBitCast has a safe replacement (Float.bitPattern, UInt32(truncatingIfNeeded:), withMemoryRebound), and the compiler even warns about some of them.

Practical guidance

  • Use MemoryLayout<T>.stride for array element spacing; size for the bytes of one value.
  • Order stored properties from the largest alignment to the smallest when millions of them live in one array.
  • Prefer small value types: copying a 16-byte struct is cheaper than reference counting a class.
  • Remember that Array, Dictionary, Set and big Strings are small handles to heap buffers.
  • Expect Optional of a pointer-like type to be free, and Optional<Int> to double the stride.
  • Avoid existentials (any P) in hot paths; use generics or some P.
  • Do not rely on exact layouts of Swift-native types in file formats or over the network. Use explicit byte-by-byte encoding with a defined endianness.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the relationship between a type's size, alignment and stride?

    Stride is the distance between consecutive array elements: the size, rounded up so the next element is correctly aligned.
  2. 2. A struct declares Bool, Int64, Bool in that order. What is its stride on a 64-bit system?

    The first Bool sits at offset 0, 7 bytes of padding follow so Int64 can sit at offset 8, the last Bool is at 16: size 17. Rounded up to alignment 8, the stride is 24.
  3. 3. Why is Bool? 1 byte while Int? is 9 bytes?

    Optionals use spare bit patterns when they exist. Bool only needs the values 0 and 1, so nil fits for free. Int has no spare patterns, so a tag byte is added.
  4. 4. What does MemoryLayout<[Int]>.size report for an array with a million elements?

    MemoryLayout measures the value stored in the variable. An Array variable is a single reference to a heap buffer; the elements live in the buffer.
  5. 5. Which is the correct way to deal with byte order in a file format?

    Native layout and byte order depend on the platform and the compiler. A file or network format should define its own layout and be written field by field with explicit endianness.

Summary

  • MemoryLayout<T> reports size, stride and alignment; use stride for arrays and offset(of:) for the position of a stored property.
  • Struct fields stay in declared order; padding is inserted for alignment, so ordering from large to small alignment saves space.
  • Int? is 9 bytes (stride 16), Bool? and optional class references cost nothing extra, and an enum without payloads needs at most a byte.
  • Array, Dictionary and class variables are one pointer; small Strings (up to 15 UTF-8 bytes) live inline in 16 bytes.
  • Existentials (any P) are 32 to 40 bytes; generics avoid that cost.
  • Bytes are little-endian on x86-64 and Arm; padding bytes have no defined value.
  • Layout of Swift-native types is not a stable contract; do not build file formats on it.

Next: Unsafe Swift