-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Consider adding AppendFormattable to StringBuilder #35047
Comments
In your example, even with the suggested The more efficient way to write this would be: sb.Append("Now = ").Append(DateTime.Now); As there's currently no I'd prefer to see this addressed with something like #28945 and dotnet/csharplang#2302. |
I'm not trying to fix the boxing of value types. I'm just trying to provide something that works today based on the intuition that, in the general case, the cost of the instantiation of a And the new method name is because the current compiler prefers But, of course, those proposals, when implemented are better. |
You can just measure :)
|
I can even measure with something more close to the code I was reviewing. 😄 private readonly StringBuilder sb = new StringBuilder();
private readonly int age = 52;
private readonly float heigh = 1.73f;
private readonly string firstName = "Paulo";
private readonly string lastName = "Morgado";
[Benchmark]
public void AppendFormat()
{
this.sb.Clear();
FormattableString fs = $"My name is {this.firstName} {this.lastName}. I'm {this.age} years old and {this.heigh}m tall.";
this.sb.AppendFormat(fs.Format, fs.GetArguments());
}
[Benchmark]
public void AppendString()
{
this.sb.Clear();
string s = $"My name is {this.firstName} {this.lastName}. I'm {this.age} years old and {this.heigh}m tall.";
this.sb.Append(s);
}
[Benchmark]
public void AppendAppend()
{
this.sb.Clear();
this.sb
.Append("My name is ")
.Append(this.firstName)
.Append(" ")
.Append(this.lastName)
.Append(". I'm ")
.Append(this.age)
.Append(" years old and ")
.Append(this.heigh)
.Append("m tall.");
}
By the way, |
The StringBuilder.Append{Line} overloads for string interpolation added in .NET 6 address this. Given that, I'm going to close this issue. Thanks. |
I see a lot of code like this:
(Well, not exactly like this, but you get my point)
The convenience of string interpolation leads to an unnecessary string instantiation.
Adding an
AppendFormattable
method toStringBuilder
(even if just as extension methods) would keep the benefits of string interpolation but without the drawbacks of the intermediate invocations ofstring.Format
.Now I can do this:
The text was updated successfully, but these errors were encountered: