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!