Buy Me a Coffee

Buy Me a Coffee!

Saturday, February 18, 2017

Memory usage in C#: StringBuilder versus String concatenate The RIGHT WAY

Thanks to some wonderful feedback, I am going to re-do my previous article on memory usage.  I am leaving the other as a warning and reminder. I have no shame in admitting my mistakes, it is the only way that we grow and learn.  ;-)
Anyway, there were several things that were not the best about the previous method I used, but the two core ones I am going to address here are my cavalier handling (or not handling) of exceptions and using Stopwatch and WorkingSet64 to roll my own bench-marking tool.
Let's examine the first one.  I knew that the only exception that I was wanting to ignore was the UnauthorizedAccessException, so why was I eating them all?  Laziness, pure and simple.  I know better!  So I fixed that by just catching that exception.  Simple.
Then I looked at the BenchmarkDotNet project and cried a little tear of joy.  Really!  It was small, but it was real.  It has more than enough bells and whistles to make me happy.  Ok, now how do I implement BenchmarkDotNet?  Super easy:
  1. Install the NuGet Package by right clicking on the project and clicking Manage NuGet Packages...
    Manage NuGet Packages

  2. Click the Browse tab and type in BenchmarkDotNet, choose the top entry and click Install
    Install BenchmarkDotNet

  3. Accept the dependencies
    Accept the dependencies
  4. And the licenses
    Accept the licenses
  5. Wrap the old nast into a new class and add attributes on some new runner methods.  It does yell at you a little if you don't run in release mode, so make that change. ;-)
Just look at the new code:
Clean and easy.  And the default output is outstanding.  It does run 16 trials by default, so I ran it against the following test directory rather than the full drive:

Here are the results as an image, so you can marvel at the pretty colors:
Benchmark Results
And here is a Gist of the full set of results:

In conclusion, well, the same thing as before.  But this time it is more accurate, and actually gives additional information.  BenchmarkDotNet is a must have arrow in your quiver.  If you show both the previous output and this output to someone, which one do you think will have the greater impact?
Keep your code clean and memory leak free!