Runtime: Proposal: StringBuilder.AppendJoin(StringBuilder separator, IEnumerable<StringBuilder> values)

Created on 7 Aug 2020  路  2Comments  路  Source: dotnet/runtime

Background and Motivation

Let's say we have a List of objects that each has a method which returns StringBuilder and we need to join all these values with another StringBuilder. If we use the current AppendJoin methods it would call StringBuilder.ToString() for each one of the items in the list,
https://github.com/dotnet/runtime/blob/5620160d496fb7e50691259f5b964de64a67cbdb/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs#L1323

With the new API we could append a StringBuilder to the main StringBuilder to reduce allocation.

Proposed API

 public sealed class StringBuilder
{
+    public StringBuilder AppendJoin(char separator, IEnumerable<StringBuilder> values)
+    public StringBuilder AppendJoin(string separator, IEnumerable<StringBuilder> values)
+    public StringBuilder AppendJoin(StringBuilder separator, IEnumerable<StringBuilder> values)
}

Usage Examples

public class Foo
{
    public StringBuilder ToStringBuilder()
    {
        var builder = new StringBuilder();
        builder.Append("Foo");
        return builder;
    }
}

public class Bar
{
    public List<Foo> Foos { get; }

    public StringBuilder ToStringBuilder()
    {
        var builder = new StringBuilder();
        builder.AppendJoin(',', Foos.Select(x => x.ToStringBuilder()));
        return builder;
    }
}

Risks

Any previous codes that are using AppendJoin<T>(string? separator, IEnumerable<T> values) and T is StringBuilder would use the new API.

api-suggestion area-System.Runtime

Most helpful comment

Why would this require new overloads? If this is a desirable optimization, couldn't it be done within the existing overloads by checking if the type of the item being appended is StringBuilder?

All 2 comments

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

Why would this require new overloads? If this is a desirable optimization, couldn't it be done within the existing overloads by checking if the type of the item being appended is StringBuilder?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Timovzl picture Timovzl  路  3Comments

matty-hall picture matty-hall  路  3Comments

nalywa picture nalywa  路  3Comments

EgorBo picture EgorBo  路  3Comments

omariom picture omariom  路  3Comments