When hashing a byte array or a stream, developers typically code it as follows:
using (var sha256 = SHA256.Create())
{
var digest = sha256.ComputeHash(byteArray);
}
Hashing the same data can be achieved using the HashData()
method, as demonstrated in the following example:
var digest = SHA256.HashData(byteArray);
Not only does this require less code, but there is also no need to worry about disposing of the SHA256
object.
Finally, consider employing TryHashData()
as demonstrated in the following example:
var hash = new byte[byteArray.Length];
var digest = SHA256.TryHashData(byteArray, hash, out var _);
Benchmark Results
The results clearly indicate that employing HashData()
is 1.03 times faster than utilizing ComputeHash()
and 1.34 times faster than TryHashData()
. Additionally, it requires fewer memory allocations.
Allocations: HashData(): 56 bytes, ComputeHash(): 240 bytes, TryHashData(): 2,072 bytes.
This is how I have it setup checking for this issue in my EditorConfig: dotnet_diagnostic.CA1850.severity = error
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf 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.
One thought on “General Performance Tip: Hashing Data”