As developers we have a tendency to lean over the functional requirements of our problem in hand but we most of the times ignore the non-functional aspect of our solution, that of code optimization. Too often I’ve noticed a tendency to pin-point the “architecture” or the “programming language” or even the computing power when it comes to determine what causes our application to be so slow. But when it comes to optimizations and code quality, the question that sometimes arises is “Would 1 ms make a difference”? I guess the answer is obviously yes.
Code optimizations are part of a different set of posts, now I will tell about a tool that will help you in this process.
Benchmarkdotnet is a great tool that is available to you on NuGet, it has a great documentation and provides insightful information regarding the performance of your application
To test this library start a new .NET Core project and under Manage Nuget Packages search for the library:
There are multiple set up options which are documented on the official website. In this example I’ve created a basic password hashing function and I will run the benchmark against it. Since my function takes a string as an input I used the ArgumentSource to notify the benchmark where to get it’s values from.
class Program { static void Main(string[] args) { BenchmarkRunner.Run(); } } [MemoryDiagnoser] [MediumRunJob, SkewnessColumn, KurtosisColumn] public class ListHelper { public IEnumerable Password() { yield return string.Join(',', Enumerable.Range(1, 31).Select(n => n.ToString())); } [Benchmark(Baseline = true)] [ArgumentsSource(nameof(Password))] public byte[] HashPwd(string password) { byte[] salt = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(salt); // Convert the plain string pwd into bytes byte[] plainTextBytes = System.Text.Encoding.Unicode.GetBytes(password); // Append salt to pwd before hashing byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length]; Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length); Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length); // Create hash for the pwd+salt HashAlgorithm hashAlgo = new SHA256Managed(); byte[] hash = hashAlgo.ComputeHash(combinedBytes); // Append the salt to the hash byte[] hashPlusSalt = new byte[hash.Length + salt.Length]; Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length); Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length); return hashPlusSalt; } }
The results :