3

tell me pls what's problem with this code C#.

        string str = string.Empty;
        for (var i = 1; i <= 1000; i++)
            str += i.ToString();

This was interview question.

2
  • No problems. It depends on what you are trying to do. Commented Mar 1, 2014 at 8:06
  • 1
    This may lead to Memory consumption problem, here + operator creates 1000 strings, use StringBuilder in such cases. Commented Mar 1, 2014 at 8:12

2 Answers 2

5

actually there is no problem with your code.

inthis case StringBuilder is more appropriate than string.

because StringBuilder is mutable whereas string is immutable.

so whenever you modify the String object using += it creates a new string object so at the end of your loop it creates many string objects.

but if you use StringBuilder: same object will be modified each time you Append the Strings to it.

You can find more info from MSDN: StringBuilder Class

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Solution :

This

    string str = string.Empty;
    for (var i = 1; i <= 1000; i++)
        str += i.ToString();

Shouldbe this

    StringBuilder str =new StringBuilder();
    for (var i = 1; i <= 1000; i++)
        str.Append(i.ToString());
Sign up to request clarification or add additional context in comments.

Comments

1

There is an answer here.

the compiler can't do anything if you concatenate in a loop and this does generate a lot of garbage.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.