I'm trying to understand why hashing of multiple hashes is much slower than one hash. In the following test I hash a file twice - first with SHA1 and then with both SHA1 and SHA256. The first execution shows the expected results - disk read dominates the time used - both took around 30 seconds (the latter around a second less despite more work).
However, on subsequent executions I get a strange result: around 10 seconds for the first and 30 for the second. The 10
implying that the original disk read took 20 seconds, and the 30
implying that it took almost no time. Which, probably, really means that for some reason, hashing once is much quicker than twice. But why?
What's happening here?
The code:
Text = TestSpeed(new HashAlgorithm[] { new SHA1Managed() }, path);
Text += " " + TestSpeed(new HashAlgorithm[] { new SHA1Managed(), new SHA256Managed() }, path);
And:
public string TestSpeed(HashAlgorithm[] algorithms, string path)
{
Stopwatch sw = new Stopwatch();
sw.Start();
byte[] block = new byte[65536];
int bytesRead = 0;
using (FileStream stream = new FileStream(path, FileMode.Open))
while ((bytesRead = stream.Read(block, 0, block.Length)) > 0)
foreach (HashAlgorithm algorithm in algorithms)
algorithm.TransformBlock(block, 0, bytesRead, null, 0);
foreach (HashAlgorithm algorithm in algorithms)
algorithm.TransformFinalBlock(block, 0, 0);
sw.Stop();
return sw.Elapsed.ToString();
}