H.G.Srivatsa said:
Hello Experts
I'm very new to software field....
Can any1 send me the advantages of Stringbuilder class over String
class
String is immutable which means that it cann be changed. Strings are
also interned, which means that if two string variables have the same
collection of characters then they are the same string object. This is
more efficient with runtime memory, and it means that the literal
strings take up less space in the application's executable file.
Since String is immutable it means that when you do any string
manipulation (eg ToLower, ToUpper etc) then a new String is created with
the results. Indeed something like this:
string s = "a";
s += "b";
Looks like the string s has the character b added to its end. In fact
this is not the case, another string is created, "ab", and s is assigned
to it. You can imagine that if you do a lot of concatenation then a lot
of string objects are created. These will *eventually* be released by
the garbage collector, but 'eventually' could be some time, during which
your application's memory usage goes up and up.
StringBuilder is designed to allow you to pre-allocate some memory and
then assign characters to it. StringBuilder will monitor the usuage of
the memory buffer and if it needs more it will automatically
re-allocate. Of course, if this happens then the old memory will stay
around until the garbage collector releases it. However, careful
analysis of your code should allow you to determine the amount of memory
you need. Once the you have finished constructing your string you can
tell StringBuilder to create an immutable String from it.
Another aspect (which I won't go in to details, just mention in passing)
is managed/unmanaged code interoperation. If the parameter of an
unmanaged function is a fixed (const) string then you can pass a String.
The interop layer will do conversion to ANSI string if necessary.
However, if you want the unmanaged function to fill a string buffer to
return a string you should not use a String, because it is immutable.
Instead, you can pre-allocate a StringBuilder (define its capacity) and
pass that to the unmanaged function. The interop layer understands
StringBuilder and treats it appropriately. When the unmanaged function
returns you use StringBuilder.ToString() to get access to the string.
Richard