Below is a “from-the-metal” comparison of walking through
- T[] where T is a reference type (class/record/
object)
- T[] where T is a value type (struct)
assuming the logical data they carry is the same.
──────────────────────────────────────────────────────────
-
Memory layout
──────────────────────────────────────────────────────────
Array header (method table ptr, length, sync-blk, …)
┌─────────────────────┐
│ ref[] │
├────────┬────────────┤
│ ref 0 │ 0x7ff…1000 │──┐ each object is elsewhere
│ ref 1 │ 0x7ff…2000 │─▶│ ┌──────────┐
│ ref 2 │ 0x7ff…3000 │─▶└─► │ obj │
└────────┴────────────┘ └──────────┘
┌─────────────────────┐
│ struct[] │
├────────┬────────────┤
│ field0 │ field1 … │ #0 contiguous, inline
│ field0 │ field1 … │ #1
│ field0 │ field1 … │ #2
└────────┴────────────┘
• Reference array = contiguous references (8 bytes on x64)
object payloads live in unrelated heap pages → pointer chasing.
• Struct array = payloads are embedded right after the header → perfect spatial locality, predictable strides.
──────────────────────────────────────────────────────────
2. CPU-side latency & cache
──────────────────────────────────────────────────────────
• Walking a ref array:
– Load reference (cheap, very cache-friendly)
– Indirect load of the actual object (may miss L1/L2)
– Two dependent memory ops → higher latency, branch predictor can’t help.
• Walking a struct array:
– Single load: data is already in the same cache line as the previous element.
– Can be vectorised by the JIT (Hardware SIMD) when the struct is POD-like.
Net effect: struct[] almost always wins for tight numeric loops (1.3×-5×).
──────────────────────────────────────────────────────────
3. JIT-generated IL/native code
──────────────────────────────────────────────────────────
IL for a simple for-loop is identical for both cases:
ldloc.0 // i
ldelem.* // ldelem.ref vs ldelem.valuetype
⋯
But at the tier-1 JIT level:
• ldelem.ref → loads an 8-byte pointer then another load.
• ldelem.valuetype → direct LEA into the array base + i*sizeof(T).
Hence fewer instructions, no additional register needed for dereference.
──────────────────────────────────────────────────────────
4. Copy semantics & in-cache size
──────────────────────────────────────────────────────────
• Reference element size is fixed (PtrSize).
• Struct element size = sizeof(T). If T ≥ 32 bytes you may start copying more bytes than you’d like every time you read the element (unless you go ref T or in T).
Rule of thumb
– Small (≤16 bytes), immutable → struct array is king.
– Large, mutable, shared among multiple structures → class array.
──────────────────────────────────────────────────────────
5. Garbage Collection behaviour
──────────────────────────────────────────────────────────
ref[]:
• Array + N objects = N + 1 GC-tracked allocations.
• During collection, GC must trace each reference in the array.
struct[]:
• Single object to track.
• No need to scan inner fields (unless they themselves contain refs).
That reduces GC pause time, especially for very large N.
──────────────────────────────────────────────────────────
6. Boxing / Interface calls / Generics
──────────────────────────────────────────────────────────
struct[] can accidentally incur boxing:
foreach (IFoo x in structArray) { … } // boxing each iteration!
The same loop over a ref[] doesn’t box because the items are already references.
Generics:
– List<T> where T is struct → JIT creates a fully specialised closed type; no boxing.
– The specialisation cost is trivial compared to the runtime win.
──────────────────────────────────────────────────────────
7. foreach vs for
──────────────────────────────────────────────────────────
for (int i = 0; i < arr.Length; i++) { … } // no copy
foreach (var s in structArr) // copies each struct by value
foreach (var o in objArr) // copies 8-byte ref
Hence with structs you often switch to a for loop or use ref readonly enumerators (C# 7.3+) to avoid the copy.
──────────────────────────────────────────────────────────
8. Micro-benchmark (BenchmarkDotNet)
──────────────────────────────────────────────────────────
public struct PointS { public int X, Y; }
public class PointC { public int X, Y; }
[MemoryDiagnoser]
public class IterBench
{
private readonly PointS[] _sv = new PointS[1_000_000];
private readonly PointC[] _cv = new PointC[1_000_000];
[Benchmark] public int SumStruct()
{
int s = 0;
for (int i = 0; i < _sv.Length; i++) s += _sv[i].X;
return s;
}
[Benchmark] public int SumClass()
{
int s = 0;
for (int i = 0; i < _cv.Length; i++) s += _cv[i].X;
return s;
}
}
Typical run (.NET 7, Ryzen 5950X):
| Method | Mean | Gen0/1/2 | Alloc |
|---|
| SumStruct | 10.2 µs | 0 / 0 /0 | 0 B |
| SumClass | 34.8 µs | 0 / 0 /0 | 0 B |
≈3.4× difference entirely from cache behaviour & pointer chasing.
──────────────────────────────────────────────────────────
9. Summary cheat-sheet
──────────────────────────────────────────────────────────
✔ struct[]
- Perfect locality, fewer GC roots, SIMD friendly
− Element copy cost, beware of boxing, cannot be null, versioning rules stricter
✔ class[]
- Cheap to copy references, polymorphism, easy mutability
− Pointer chasing, higher GC pressure, two loads per access
If your elements are
• small (≤16 B)
• immutable or rarely mutated
• used in math/physics/graphics loops
→ Use a struct array (or Span<T> / Memory<T>).
Otherwise stick to class array for flexibility.
⚠ Never just “convert everything to struct”; large structs kill performance because each access moves the entire blob.
Hope this gives you the low-level trade-offs you were looking for! 🚀