I have recently run into a few performance problems with my (code name) NTorrent app –  it simply ate too much processor time even though most of the time it did nothing (that’s what I thought at least).

Since I had a lot of time to design it, I did not expect the design to be an issue and jumped straight into the profiler. I downloaded JetBrains’s dotTrace trial because I expected the problem to be quickly found.

Since I’m writing this, you can for sure guess I was wrong – took me a few days of on and off profiling until I finally figured it out. In the end, profiler did not help me, but it did point in the right direction, if only I was able to see the forest from the trees (or is it the other way around, I always forget).

Take the following snippet of code for example:

internal static int TotalSpace(List<List<byte>> list)
{
  int total = 0;
  list.ForEach(delegate(List<byte> buf) { total += buf.Count; });
  return total;
}

According to the profiler, quite a lot of time was spent in this little function. Now, I looked at the places this code was called from and the frequency of calls and all that – everything looked fine. Probably out of despair and frustration I concluded that the problem must have been in the fact that I am using anonymous delegate instead of straightforward solution like this one:

internal static int TotalSpace(List<List<byte>> list)
{
  int total = 0;
  foreach (List<byte> bytes in list)
    total += bytes.Count;
  return total;
}

This of course helped improve performance exactly 0%  Why would an anonymous delegate be significantly slower anyway? It must be me… and it was me.

I did not take into account the size of list that this code was going through. I assumed the size is very low, but I never checked, until I finally put a breakpoint and just looked at the list’s size. Turns out that because of a trivial issue I knew about and ignored for a few months another piece of code that maintained the list degenerated it into thousands of elements, growing over time.

About 5 lines of code later, and a few minutes of testing, my performance problem went away. This is yet another example how even the best tools out there will not help your bad design decisions. Most of the time the performance problems are architectural, and if you’re lucky, trivially solvable.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments