A few months ago i was wondering what is the purpose of the stringbuilder class in C#, if what it can do can also be done in a simple String/string variable type... and is done, imao, with more ease.
For example let's look at string concatenation:
//StringBuilder
StringBuilder sbExample = new StringBuilder();
sbExample.Append("Some ");
sbExample.Append("Text Here...");
return sbExample.ToString();
//String
String strExample = "Some ";
strExample = strExample + "Text Here...";
return strExample;
In this example, it is much easier to perform string concatenation with a plain simple string type than the stringbuilder, now what exactly is the difference between the two?
The answer: i've been reading the MS Book Application Foundation and here i've learned that a string memory address is immutable... if you concatenate or replace the string value, it does not overwrite its current memory location and instead allocates a new memory location for the new string value, meanwhile with the stringbuilder it always use the same memory it is allocated with whenever you try to modify it's value...
eureka! now i know, for better optimization, when dealing with strings use stringbuilder instead of the basic string value type, there might be an increase in the effort in coding, but what is a little sacrifice for a little more optimized performance.
small things can become big things too ;)
No comments:
Post a Comment