Search code examples
c#performancedictionaryintegerhashcode

What is the most efficient way to key a xyz pair in a C# dictionary?


I have a bunch of objects with xyz pairs (bytes) that I need to add to a dictionary. It's in the tens of thousands and I'm not sure what the most efficient way would be to go about it.

Would something like this work?

Dictionary<int, Object> table;

table.Add(new byte[3]{ x, y, z }.GetHashCode(), object);

Or would it be better to use a byte[3] and an equality comparer?


Solution

  • If the key is always 3 bytes, it seems like a ValueTuple is appropriate.

    Dictionary<(byte, byte, byte), object> table;
    
    table.Add((1,2,3), new object());
    

    Unlike a byte[], ValueTuple is a value type, so it won't cause additional heap allocations when you access the dictionary.

    You can also pack the 3 bytes inside an int with bit shifts. This might be faster than a value tuple.

    byte b1 = ...;
    byte b2 = ...;
    byte b3 = ...;
    int key = (b1 << 16) | (b2 << 8) | b3;
    
    Dictionary<int, object> table = new();
    table.Add(key, new object());