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 public string GetIframeIds() {     var result = new StringBuilder();     var first = true;     foreach (var iframe in _iframes)     {         if (!first) result.Append(',');         else first = false;         result.Append("'" + iframe.ClientID + "'");     }     return result.ToString(); } … and just had to rewrite it to this: Updated version public string GetIframeIds() {     return string.Join(",", _iframes.Select(ifr => "'" + ifr.ClientID + "'")); } 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!

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for jQuery. 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 daughter. 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.