Runar Ovesen Hjerpbakk

Science-based software development

On structs

The 2014 book Writing High-Performance .NET Code contains tips on coding effective C#, above and beyond the Zen of Performance. It made me consider the usage of value types, struct instead of class.

By using struct for small structures, we achieve less memory usage, better memory locality and fewer garbage collections. Arrays of structs have good memory locality, utilising the CPU caches and improving performance due to more cache hits.

Design guidelines

TypeSize
sizeof(sbyte)1
sizeof(byte)1
sizeof(short)2
sizeof(ushort)2
sizeof(int)4
sizeof(uint)4
sizeof(long)8
sizeof(ulong)8
sizeof(char)2
sizeof(float)4
sizeof(double)8
sizeof(decimal)16
sizeof(bool)1

Recommendation

Use a struct when:

For all else, use class.

Example

public struct WidgetInformation : IEquatable<WidgetInformation>
{
  private readonly Guid id;
  private readonly string name;

  public WidgetInformation(Guid id, string name)
  {
    this.id = id;
    this.name = name;
  }

  public Guid Id { get { return id; } }
  public string Name { get { return name; } }

  public override bool Equals(object obj)
  {
    return obj != null && obj.GetType() == GetType() && base.Equals((WidgetInformation)obj);
  }

  public bool Equals(WidgetInformation other)
  {
    return id == null ? other.id == null : id.Equals(other.id);
  }
  
  public override int GetHashCode()
  {
    return id == null ? base.GetHashCode() : id.GetHashCode();
  }
}