Skip to content

[API Proposal]: StringBuilder.AppendJoin but instead of Select'ing values use StringBuilder itself #114095

Open
@stanislav-a-frolov

Description

@stanislav-a-frolov

Background and motivation

As far as I understand we could benefit in performance in case of AppendJoin with custom string representation of joined collection values representation if we build that representation by hand instead of creating new string for each element.
For example the following code creates new string for each iteration:

sb.AppendJoin(" ", context.Variables.Select(t => $"${t.Name}: {t.Type}"));

API Proposal

namespace System.Text;

public class StringBuilder
{
    public static StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values, Action<StringBuilder, T> appendFunc);
    public static StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values, Action<StringBuilder, T> appendFunc);
}

API Usage

sb.AppendJoin(" ", context.Variables, 
    (sb, t) => sb
        .Append("$")
        .Append(t.Name)
        .Append(": ")
        .Append(t.Type));
// or
sb.AppendJoin(" ", context.Variables, (sb, t) => sb.Append($"${t.Name}: {t.Type}"));

Alternative Designs

Possibly some interpolated string API (e.g. like Append(StringBuilder+AppendInterpolatedStringHandler)) could do

namespace System.Text;

public class StringBuilder
{
    public static StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values, Func<T, StringBuilder+AppendInterpolatedStringHandler> toStringFunc);
}

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.RuntimeuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions