Pieces of C# – long and short

by Oliver 9. August 2014 12:52

Today, I found this dusty piece of code in our code base:

Stone-age version
  1. public string GetIframeIds()
  2. {
  3.     var result = new StringBuilder();
  4.     var first = true;
  5.     foreach (var iframe in _iframes)
  6.     {
  7.         if (!first) result.Append(',');
  8.         else first = false;
  9.         result.Append("'" + iframe.ClientID + "'");
  10.     }
  11.     return result.ToString();
  12. }

… and just had to rewrite it to this:

Updated version
  1. public string GetIframeIds()
  2. {
  3.     return string.Join(",", _iframes.Select(ifr => "'" + ifr.ClientID + "'"));
  4. }

I couldn't bear but run some micro-performance test on these code snippets since StringBuilder is usually quite fast. I ran each of the snippets with an _iframes length of 30 in a loop of 10.000 iterations and yes, the first version is faster with 215ms vs. 360ms. But then, in production I run that code block only once per request, not 10.000 times as in the test. Spending 21ns or 36ns in that method won't make any significant difference, especially when looking at request execution times of beyond 100ms.

Why should you or I care?

The second code block is arguably easier to read, quicker to write, and harder to get wrong.

Happy coding!

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.