Would it be particuarly bad to use a StringBuilder in a C# getter?

The getter would get a message about the state of the struct it's in, which is defined by a combination of the struct's properties, which are finite.

First, this isn't about micro-optimization, I just think that:

StringBuilder msg = new StringBuilder();
...
msg.AppendLine("static string");
...

looks cleaner then:

String msg = String.Empty;
...
msg = String.Concat(msg, "static string", System.Environment.NewLine)
...

so just an aesthetic choice.

The msg variable has to be initialized empty either way, so the extra line doesn't bug me. But how bad is it to construct a new StringBuilder in a field that returns a string?

EDIT I just wanted to know if putting a StringBuilder constructor in a getter was going to open up a huge can of worms, be ridiculous overhead, some never use constructors in getters kind of anti-pattern thing, etc... not to know everybody's favorite most performant way to concat non-looping strings.

EDIT2 What is the usual, best practice, performance threshold for a getter and does a StringBuilder constructor fall below that?


Why not do this?

msg + "static string" + Environment.NewLine

It will compile to the same as your second example.

Update

You changed your code so that it appears that you want to create a very large string containing lots of lines.

Then I guess it's fine to use StringBuilder , but I'd suggest that you make it a method (how about overriding ToString ?) rather than a property so that callers are less likely to assume that it's cheap to call.


From a performance point of view, with the data supplied (three substrings), the String.Concat is better.

But, if inside the getter, you have lines like if(state == 0) that disrupt the efficiency of Concat or + operator then use StringBuilder for its good efficiency in string memory handling and for its clear syntax on AppendLine. Look at this site for data on StringBuilder vs Concat vs + and for some info on StringBuilder tips and mistakes


String.Concat function outperforms the StringBuilder by 2.3 times when not using lots of strings. Also,if for example you write code like "a" + "b" + "c" + "d" + "f" the compilter will compile it to use string.Concat(string[]) in the IL code.

链接地址: http://www.djcxy.com/p/31496.html

上一篇: Java初始化对象设计

下一篇: 在C#getter中使用StringBuilder会特别糟糕吗?