1

I am having doubt in whether to use string or string builder to append html elements like "div" and others in my page in mvc. Is there any other approach for this thing.

Thanks.

1
  • 1
    atleast do upvote if you like answer Commented Apr 4, 2011 at 11:27

7 Answers 7

2

I read that Microsoft recommends using StringBuilder when you predict to have more then 6 concatenations.

Sign up to request clarification or add additional context in comments.

Comments

2

StringBuilder is the way to go. A String holds a reference to an immutable (fixed) string, and appending to a string is horribly inefficient. If your intention is to repeated perform appends then this is exactly what the StringBuilder was designed for.

2 Comments

Inmutable, that means any change to the string causes the runtime to create a new string and abandone the old one.
@rob: Yeah - that's what I meant - but your explanation is much clearer!
2

You should use StringBuilder if you change string a lot (add, remove, change, replace characters) because it's more efficient. If you do simply operation you should use string.

The problem with string is that it's immutable, so operatrion

string text = myStringVariable + "new string"

causes that the new instance of the text variable will be created. If you do many operation on string class then you will have many instances of string objects.

Comments

1

Whenever you have perform appending texts, you should always use stringbuilder.

Using string would repeatedly create new instances of a string and hence inefficient.

Comments

1

check this post for the depth knowledge about : Why to use StringBuilder over string to get better performance

Comments

0

To be honest and saying something unusual at the end it really does not matter. The differences are so small that you shouldn't care about this and you should invest the time in other things that make difference.

Check this article of Jeff where all this is explained (also in a web environment, when he was creating StackOverflow).

Coding horror article about why does not matter how do you create strings

1 Comment

Great view.But can you just explain me regarding the immutable thing i just don't understand it.Thanks in advance.
0

String bulider Can Be Used When More than One String to be concatenated. StringBuilder which is more efficient because it does contain a mutable string buffer. .NET Strings are immutable which is the reason why a new string object is created every time we alter it (insert, append, remove, etc.).

1 Comment

Thanks.Is there a limit on hw many times in our project we can use string builder ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.