tezvyn:

Struct versus class performance and memory tradeoffs

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

value versus reference semantics and allocation cost.

OUTLINE

structs are value types, often stack-allocated with no ARC; classes are heap-allocated reference types with retain counts.

RED FLAG

claiming structs are always faster.

WHY THIS MATTERS The interviewer probes whether you reason about allocation, copying, and reference counting rather than reciting that structs are values and classes are references.

A GOOD ANSWER COVERS Structs are value types. Small ones are often kept inline or on the stack, copied by value, and incur no automatic reference counting, so they avoid heap allocation and ARC atomics. Classes are reference types allocated on the heap; every store, pass, or capture adjusts a retain count using atomic operations, and deallocation runs through the runtime. Value semantics also remove a whole class of aliasing bugs because no two variables silently share storage.

WHEN STRUCTS WIN Small, short-lived, identity-free data such as coordinates, sizes, or model rows. They cut allocation churn and let the optimizer keep fields in registers.

WHEN CLASSES WIN When you need shared mutable state observed from many places, a stable identity, deinit semantics, inheritance, or Objective-C interop. A class is also preferable when a type holds a large payload that would be expensive to deep-copy on every assignment and you cannot lean on copy-on-write.

COMMON WRONG ANSWERS Claiming structs are always faster. A large struct copied repeatedly across function boundaries can cost more than passing one class reference. Forgetting that standard collections use copy-on-write so a struct holding an Array does not deep-copy until mutated.

LIKELY FOLLOW-UPS What is copy-on-write and how does it change the calculus? How does capturing a struct in a closure differ from capturing a class? When does the compiler promote a struct to the stack versus the heap?

ONE CONCRETE EXAMPLE A particle system updates ten thousand entities per frame. Modeling each particle as a small struct in a contiguous array keeps the data cache-friendly and free of per-particle ARC. Switching to classes added heap allocation and retain traffic that showed up clearly as overhead in the Time Profiler.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.