Michał Turczyn
Michał Turczyn

Reputation: 37367

Memory align of instances of classes

I have read recently interesting article about performance.

There, author defined struct as follows:

public struct DecisionTreeNode
{
  public short ShortValue;
  public float FloatValue;
  public byte ByteVal1;
  public byte ByteVal2;
}

Inseance of this struct is 8 bytes.

All clear, but then he suggested that in order to gain performance, author writes:

This [memory] alignment issue means it can be a fair bit more expensive to load the non aligned value. Luckily, the fix is really simple, you just swap the order of the fields in your class definition.

So he does that:

public struct DecisionTreeNode
{
  public float FloatValue;
  public short ShortValue;
  public byte ByteVal1;
  public byte ByteVal2;
}

How order fo fields in a class can affect way of storing instance in memory? How it affects mentioned alignment?

Upvotes: 1

Views: 372

Answers (1)

you have a very good explanation here :

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=netframework-4.7

https://kalapos.net/Blog/ShowPost/DotNetConceptOfTheWeek13_DotNetMemoryLayout

Everything is all about the Pack field (is the size of its largest element or the specified packing size attribute => [StructLayout(LayoutKind.Sequential, Pack=X)] whichever is smaller).

According to the Pack field the struct will group fields sequentially into a Pack size and add empty bytes to fit the Pack field.

struct => 1byte + 8byte + 1byte => Pack field => 8 => 8 + 8 + 8 = 24bytes

struct => 1byte + 1byte + 8byte => Pack field => 8 => 8 (1+1+6 empty bytes) + 8 = 16 bytes.

As you can see always group fields using the Pack field size.

Upvotes: 1

Related Questions