What is the difference between String and StringBuilder in C#?

Dung Do Tien Oct 30 2021 117

When I'm learning C# and I learn more about data type support in C#. I see it provided string and StringBuilder

I feel it the same together, You can see two blocks of code below, I got the same result:

static void Main(string[] args)
{
    // 1. String
    string doc = "paragrap 1 /n";
    for (int i = 2; i <= 10; i++)
    {
        doc += string.Format("paragrap {0} /n", i);
    }

    Console.Write(doc);

    // 2. StringBuilder
    StringBuilder docBuilder = new StringBuilder();
    docBuilder.Append("paragrap 1 /n");
    for (int j = 2; j <= 10; j++)
    {
        docBuilder.AppendFormat("paragrap {0} /n", j);
    }

    Console.Write(docBuilder.ToString());
}

SO What is the difference between string and StringBuilder in C#? I when to know when I can use StringBuilder or string?

Can you tell me know the best practices for them, You have been using them in your project.

Thank you for your explanation.

Have 2 answer(s) found.
  • S

    Shilpi Tara Oct 30 2021

    With my experience, I list out some other differences between them as below:

    The main difference is:

    += operator for string, OS will allocate a new location in memory, If you loop 100 times, it will allocate 100 times. This action will make RAM increase and be very slow.

    Append() method of StringBuilder when not required to allocate a new position in RAM, it will append to same location in RAM when it instance. So this feature makes your app run FASTER.

    So when you have to concat string much time, You should be using StringBuider to do and vice versa you can use string to help your code clear and fast.

    => With your example, you should use StringBuilder

  • H

    Hieu Nguyen Oct 30 2021

    String

     String is immutable, Immutable means if you create a string object then you cannot modify it and It always creates a new object of string type in memory.

    StringBuilder

    StringBuilder is mutable, which means if create a string builder object then you can perform any operation like insert, replace or append without creating a new instance every time.it will update string at one place in memory doesn't create new space in memory.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close