2

I would expect the code below (from the Exception class in .Net framework) to use a StringBuilder to build a string and then return a builder.ToString() instead of using the "+" operator on the existing string, which ends up creating a new string everytime.

I expect folks writing .Net source code to follow the best practices where ever possible, therefore I want to double check if this is still somehow optimal

private String ToString(bool needFileLineInfo, bool needMessage) {
    String message = (needMessage ? Message : null);
    String s;
    if (message == null || message.Length <= 0) {
        s = GetClassName();
    }
    else {
        s = GetClassName() + ": " + message;
    }

    if (_innerException!=null) {
        s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) 
              + Environment.NewLine 
              + "   "
              + Environment.GetResourceString("Exception_EndOfInnerExceptionStack");

    }

    string stackTrace = GetStackTrace(needFileLineInfo);
    if (stackTrace != null)
    {
        s += Environment.NewLine + stackTrace;
    }

    return s;
}
Sushant
  • 1,074
  • 2
  • 13
  • 21
  • 2
    Not a bug. At worst a minor inefficiency, but chances are the compiler is going to optimise it for you anyway. – John3136 Aug 16 '16 at 01:55
  • 3
    Nobody will be able to provide a definitive answer to this, as it's all speculation. My guess: since it's an exception it should only happen in exceptional cases. If it's happening, you're pretty much boned anyway. – i_am_jorf Aug 16 '16 at 01:56
  • Maybe it's faster this way: http://stackoverflow.com/questions/1612797/string-concatenation-vs-string-builder-performance – Blorgbeard Aug 16 '16 at 02:11
  • 3
    Somewhat speculative, but I would suggest you think about *when* an exception is being created. StringBuilder would allocate an initial buffer, which won't always be possible depending on what sort of meltdown the application is having. – slugster Aug 16 '16 at 03:24

1 Answers1

5

It's impossible to know for sure why the author of the code chose this implementation, without asking the author of the code.

That said, it's worth keeping in mind that the general guidance to prefer StringBuilder over simple string concatenation applies mainly to looping scenarios where you have arbitrarily large iteration counts.

In the example above, the main part of the method should wind up calling the Concat() method, which should do a better job of creating a single new string object from the inputs than appending each part iteratively using StringBuilder. To introduce StringBuilder for the other concatenation, especially when they are not always going to happen (since they are conditional), could very well be less optimal in the common scenarios.

See e.g. String concatenation vs String Builder. Performance, where this difference is specifically called out.

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136