none
String Interpolation vs StringBuilder.AppendFormat RRS feed

  • Question

  • I would like to know the best practise behind concatenating strings and make sure memory would be used sufficiently and compute fast.

    I have a loop that would bind number of string and Append into a string builder object (Don'b confused with variable names as it is an example)

    StringBuilder strObj = new StringBuilder();
    
    foreach (object obj in objArray)
    {               
        strObj.AppendFormat("Value {0}{1} in {2} in {3}.", obj.A, obj.B, obj.C, obj.D).AppendLine();
    }

    I would like to know above way is better or will there be another way to implement more efficiently? Or could I include interpolation into StringBuilder? because I was suggested to use string interpolation instead

    Thanks in advance

     


    • Edited by Gayan19911212 Thursday, March 26, 2020 2:50 AM Extra info
    Thursday, March 26, 2020 2:48 AM

All replies

  • I did a quick google search because I was thinking there would be no difference and this seems to confirm my guess (of course, you can just test yourself)

    https://stackoverflow.com/questions/32342392/string-interpolation-vs-string-format


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Thursday, March 26, 2020 3:51 AM
    Moderator
  • @naomi N, thanks for the reply but it is related to string system type not StringBuilder. If i'm not wrong, string.Format & string.Concar uses StringBuilder to merge string values.
    Thursday, March 26, 2020 4:35 AM
  • Hi Gayan19911212,

    Thank you for posting here.

    According to the introduction of Microsoft documentation.

    String.Format works well when you build strings from a small number of component strings.

    In other cases, such as combining strings in a loop, you don't know how many source strings to combine, and the actual number of source strings can be large. 

    The StringBuilder class is designed for these situations

    How to concatenate multiple strings (C# Guide)

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, March 26, 2020 6:58 AM
  • I was thinking your question was just about the loop code and you were trying to decide between AppendFormat vs Append with string interpolation. In this case it would be no difference or it would be negligible.

    For building the whole string I would still use StringBuilder the way you showed. E.g. declare it outside the loop.


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles



    Thursday, March 26, 2020 2:03 PM
    Moderator
  • Hello,

    Here is an option which uses string interpolation. 

    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Active { get; set; }
        public string Display => $"{FirstName} {LastName} is Active: {(Active ? "Yes":"No")}";
    }

    Demo

    private readonly List<Person> _persons = new List<Person>()
    {
        new Person() {FirstName = "Karen", LastName = "Payne", Active = true},
        new Person() {FirstName = "Mary", LastName = "Adams", Active = true}
    };
    private void button1_Click(object sender, EventArgs e)
    {
        var sbPeople = new StringBuilder();
    
        _persons.Select(person => person.Display).ToList()
            .ForEach(data => sbPeople.AppendLine(data));
    
        Console.WriteLine(sbPeople.ToString());
    }

    Or use string concatenation.

    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Active { get; set; }
        public string Display => 
            string.Concat(FirstName, LastName, 
                " is active ", (Active ? "Yes" : "No"));
    }
    Don't have time to do a comparison between the two but can't imagine much of a difference.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, March 26, 2020 2:43 PM
    Moderator
  • The implementation of AppendFormat can be investigated here: https://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs,2c3b4c2e7c43f5a4.

    Maybe consider this alternative approach too:

       strObj

          .Append( "Value ")

          .Append( obj.A)

          .Append( obj.B)

          .Append( " in ")

          .Append( obj.C)

          .Append( " in ")

          .Append( obj.D)

          .AppendLine( ".");

     

    • Edited by Viorel_MVP Thursday, March 26, 2020 3:07 PM
    Thursday, March 26, 2020 3:01 PM