Question

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.

Was it helpful?

Solution

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());

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top