A struct against a class

A struct stores its fields where the variable is; a class stores a reference to an object on the heap. An array of a million structs is one block of eight million bytes; an array of a million class instances is a million objects and a million references. This lesson measures both the bytes and the time on the same data.

The memory of the two arrays

The types are deliberately simple and use public fields, so that the comparison measures the layout and not the cost of a property call. The program fills both arrays and asks the runtime how many bytes each fill allocated:

using System.Diagnostics; const int Count = 1_000_000; var before = GC.GetAllocatedBytesForCurrentThread(); var points = new Point[Count]; for (var i = 0; i < Count; i++) { points[i] = new Point(i, i + 1); } var structBytes = GC.GetAllocatedBytesForCurrentThread() - before; before = GC.GetAllocatedBytesForCurrentThread(); var classes = new PointClass[Count]; for (var i = 0; i < Count; i++) { classes[i] = new PointClass(i, i + 1); } var classBytes = GC.GetAllocatedBytesForCurrentThread() - before; Console.WriteLine($"struct mb {(double)structBytes / (1024 * 1024):F1}"); Console.WriteLine($"class mb {(double)classBytes / (1024 * 1024):F1}"); Console.WriteLine($"struct per item {(double)structBytes / Count:F1}"); Console.WriteLine($"class per item {(double)classBytes / Count:F1}"); var structRuns = new List<double>(); var classRuns = new List<double>(); long structSum = SumStructs(points); long classSum = SumClasses(classes); for (var run = 0; run < 5; run++) { GC.Collect(); var watch = Stopwatch.StartNew(); for (var pass = 0; pass < 10; pass++) { structSum += SumStructs(points); } watch.Stop(); structRuns.Add(watch.Elapsed.TotalMilliseconds); GC.Collect(); watch = Stopwatch.StartNew(); for (var pass = 0; pass < 10; pass++) { classSum += SumClasses(classes); } watch.Stop(); classRuns.Add(watch.Elapsed.TotalMilliseconds); Console.WriteLine($"run {run + 1} struct {structRuns[^1]:F2} class {classRuns[^1]:F2}"); } Console.WriteLine($"struct min {structRuns.Min():F2} median {structRuns.Order().ElementAt(2):F2}"); Console.WriteLine($"class min {classRuns.Min():F2} median {classRuns.Order().ElementAt(2):F2}"); Console.WriteLine($"sums {structSum > 0 && classSum > 0}"); static long SumStructs(Point[] items) { long sum = 0; for (var i = 0; i < items.Length; i++) { sum += items[i].X + items[i].Y; } return sum; } static long SumClasses(PointClass[] items) { long sum = 0; for (var i = 0; i < items.Length; i++) { sum += items[i].X + items[i].Y; } return sum; } struct Point { public Point(int x, int y) { X = x; Y = y; } public int X; public int Y; } sealed class PointClass { public PointClass(int x, int y) { X = x; Y = y; } public int X; public int Y; }

dotnet run

struct mb 7.6
class mb 30.5
struct per item 8.0
class per item 32.0
run 1 struct 58.49 class 66.51
run 2 struct 50.63 class 94.84
run 3 struct 53.35 class 71.03
run 4 struct 53.02 class 65.85
run 5 struct 50.90 class 98.71
struct min 50.63 median 53.02
class min 65.85 median 71.03
sums True

Eight bytes per point is the two integers, and the array header is the small remainder. Thirty-two bytes per point is four times as much: eight for the two integers, eight for the object header and eight for the method table pointer, which rounds to twenty-four, plus the eight-byte reference in the array. One million points therefore cost 7.6 MB one way and 30.5 MB the other, before the collector has done anything.

The measured time

The second half of the same program touches every element ten times per measurement and repeats that five times, collecting before each pass so that the garbage of the previous one does not land inside the next measurement. The two sums are kept in variables outside the loop, so the loop is not optimized away. Its output is the ten lines of the run above, after the four byte lines.

Why the struct wins

When a class is right

A struct is not the default. It has no identity: two points with the same coordinates are interchangeable, and a copy is a copy. A class is the right type when the object has an identity that matters, when several parts of a program must see the same instance, when it is large, or when it is mutated through a reference. The rule of thumb of the framework is a struct of sixteen bytes or less that behaves like a value, such as a point, a money amount or a range; everything else is a class.

Exercises

  1. Change the fields to auto-properties and measure again; explain the difference.
  2. Make Point a readonly struct and check that the output does not change.
  3. Add a string Name field to both types and predict which one allocates more.
  4. Move the GC.Collect calls out of the loop and see how the class numbers change.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many bytes did one point cost in the struct array?

    Answer

    8

    Two int fields are eight bytes, and the measured per-item figure was 8.0.

  2. How many bytes did one point cost in the class array?

    Answer

    32

    The object header, the method table pointer, the fields and the reference came to 32.

  3. What does this program print? var a = new Point(1, 2); var b = a; b.X = 9; Console.WriteLine(a.X); struct Point { public Point(int x, int y) { X = x; Y = y; } public int X; public int Y; }

    Answer

    1

    A struct assignment copies the fields, so the second variable is independent.

  4. Why is an array of classes larger than an array of structs?

    Answer

    Each element is a reference to a separate object with a header

    The measured class array was four times the struct array for the same data.

  5. What does this program print? var a = new Box(1); var b = a; b.X = 9; Console.WriteLine(a.X); class Box { public Box(int x) => X = x; public int X; }

    Answer

    9

    Both variables refer to one object, so the change is visible through both.

  6. When is a class the better choice?

    Answer

    When the object has an identity that several parts must share

    A value has no identity; a shared mutable object needs one.

  7. What did the measured medians show?

    Answer

    The struct array was faster: 53.02 ms against 71.03 ms

    All five pairs favored the struct array, and the medians are on the page.

  8. Why did the benchmark use public fields instead of properties?

    Answer

    To compare the layout without the cost of a property call

    A getter may be inlined, but a layout comparison should not depend on that.

  9. What does this program print? Console.WriteLine(default(Point).X); struct Point { public int X; public int Y; }

    Answer

    0

    The default of a struct has every field at its default, which is zero for an int.

  10. What does a readonly struct prevent?

    Answer

    Changing its fields after construction

    The compiler refuses an assignment to a field of a readonly struct.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev