Game Development Reference
In-Depth Information
Note
Calling ToString() on a StringBuilder object will simply reference the internal character array,
but a copy operation occurs as soon as the result is assigned to a string object and further opera-
tions are performed on the StringBuilder . The recommended approach is to only call
ToString() after all modifications on the StringBuilder are complete. Otherwise, it is advis-
able to use the ToString() overload that allows only a substring of the internal character array
to be returned.
StringBuilder manages an internal character buffer that is allocated during instan-
tiation. The initial capacity defaults to an array of 16 characters, but you can spec-
ify a different value for the initial capacity as a parameter in the constructor. When
an operation requires that the internal size of the StringBuilder be increased, a new
array that is double the size of the old one is created, and the old data is copied
into the new array. The reallocation is quite expensive, and it should be avoided as
much as possible. It is highly recommended that you explicitly set the initial capac-
ity if you have enough information to estimate the value that works best for your
situation.
There are some downsides to working with a StringBuilder object over a String
object. The first downside is that StringBuilder only implements a fraction of the
functions offered by String . StringBuilder also incurs a significant overhead cost
when first initialized, so there are times where using StringBuilder for only a hand-
ful of manipulations can actually decrease your performance. The rule of thumb
is to only consider using StringBuilder when the number of manipulations reach-
es double digits. StringBuilder is great to use when appending strings within a
loop. There is no real definitive answer on when to use StringBuilder , because the
performance is dependent on system parameters and design. It may not be such a
bad idea to profile critical code when using StringBuilder or another formatting
mechanism to determine which approach is faster.
Concatenating strings is a form of string formatting, but there are additional per-
formance increases that can be investigated. String.Concat() is, by far, the fastest
and most efficient way to join a couple of strings together. Use this method over
anything else if you can combine all your strings in one call to String.Concat() .
Otherwise, you can resort to a more flexible mechanism like StringBuilder if you
need to join many strings together. Never use normal String instances and the
concatenation operator to join strings together; this is the most inefficient way you
could possibly use to accomplish the task.
 
Search Nedrilad ::




Custom Search