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.
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.
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.
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.
check this post for the depth knowledge about : Why to use StringBuilder over string to get better performance
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
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.).