Game Development Reference
In-Depth Information
It is a common mistake to think that checking whether the length of a string is zero
is faster than comparing the string to the empty string constant. There is a sliver
more performance when checking the length because only the string metadata
must be examined, but this increase is marginal and it is doubtful that you will see
any measurable performance bonus. It is important to note that you should use
the canonical String.Empty instance as a constant when comparing against an
empty string rather than “” since an allocation will be avoided in this case.
String Formatting
Having the ability to insert, remove, and replace data inside strings is a common
task in almost every application. This functionality is provided through a couple
of mechanisms of the .NET platform and class framework. The first mechanism,
also the easiest to use, is the ToString() method that is available on data types that
inherit from System.Object . The default behavior of this method is to return the
full name of the type, though it can be overridden to support extended function-
ality. The typical implementation will return a partial representation of the class
with the help of the member variables inside the class. Pretty much all the string
formatting features of the .NET framework boil down to using ToString() at some
point. Therefore, it is important that you make sure that this method performs
efficiently and quickly.
Another formatting mechanism is String.Format , which functions like sprintf in
the C realm. This function is used to format a string against a pattern where certain
tokens are substituted with values in the supplied arguments array. This function
is perhaps the slowest of the bunch, because it lacks the efficiency of type over-
loading provided by a class like StringBuilder , causing a number of boxing and
unboxing operations to occur. Classes can also inherit from IFormattable to extend
the formatting capabilities of ToString() .
One of the biggest slowdowns when dealing with strings is that they are
immutable, which means that any time a string is modified, a new string object is
created. Immutable strings are great when they are shared frequently and are mod-
ified infrequently. Reading is cheap in terms of performance because locking or
reference counting is unnecessary, and you can avoid abstraction and sharing
schemes. The class framework provides the StringBuilder class, which is used to
perform high-performance string operations against a mutable Unicode character
array. After modifications on the string within a StringBuilder are complete, you
can call ToString() to retrieve the contents of the internal string.
Search Nedrilad ::

Custom Search