Hacker News new | ask | show | jobs
by xnorswap 670 days ago
If they are small, then there can be a significant performance advantage to using a struct.

Imagine you have a Dictionary<TKey,TValue>. (That is, a dictionary (hash lookup) from type TKey to type TValue ).

Imagine your choice of key is a composite of 4 bytes, and you want to preserve the meaning of each, so let's say you define a class (shorthand to avoid all the get/set cruft):

    class MyKey {
       byte A;
       byte B;
       byte C;
       byte D;
    }
When you profile your memory usage, to your horror you discover you actually have a keysize of 64 bits for the reference to the location on the heap.

If however you use a struct, then your key is actually the 4 bytes that defines your key.

In modern .Net, you'd probably be better off defaulting to use a record (correction: record struct) type for this purpose unless you have very specific reasons for wanting fine-grained control over memory layout with the StructLayout Attribute.

See this article for using StructLayout:

https://learn.microsoft.com/en-us/dotnet/api/system.runtime....

1 comments

It should be a record struct, as record defaults to class.
Thanks for that correction.