Reference Type & Structure Performance: Hashing Classes, Records, and Structures

To generate a SHA256 hash for a class, record, or structure, you can utilize the following code snippet:

public static string ComputeSha256Hash(object obj)
{
    // Create a SHA256
    var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(obj.ToJson()));

    // Convert byte array to a string
    var sb = _stringBuilderPool.Get();

    try
    {
        for (var byteIndex = 0; byteIndex < bytes.Length; byteIndex++)
        {
            _ = sb.Append(bytes[byteIndex].ToString("x2", CultureInfo.InvariantCulture));
        }

        return sb.ToString();
    }
    finally
    {
        _stringBuilderPool.Return(sb);
    }
}

Next, let’s evaluate the performance of hashing these three distinct types.

Benchmark Results

As evident from these results, hashing a reference type (class) is 1.02 times faster than a value type (structure) and 1.05 times more performant than a record type. Please note that these findings are provided for your reference.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.