| One of the ways
that C# makes it easier to develop network programs is the manipulation
of strings. As we will see later, much of the effort in socket
programming is string manipulation. It is amazing how many security
holes start with simple buffer overflows. C# handles strings
in two different ways and you are going to want to get to know
them.
Look at this code snippet and think about what is going on.
String astring
= new string(“hello”);
astring+= “ “;
astring +=”world”;
Console.WriteLine(“My string
= ‘{0}’”, astring);
Instantiate a string and then append it twice right? Logically
this is true but .NET actually does not do it that way. When
you create a string a set amount of memory is allocated and
that allocation cannot be changed. This means that strings are
immutable. So when you modify a string C# creates a new memory
space for it and flags the original one for the next cycle of
garbage collection. The creation of a new memory space, placing
the new value in it, and pointing to it creates overhead. Garbage
collection is only a partial solution. The original memory is
not reclaimed until the garbage collector gets around to it.
Now look at the example above. The process of creating the new
string and abandoning the old one actually happens twice, leaving
3 separate strings allocated in memory.
Instead you should use the StringBuilder class
which is in the System.Text namespace. This saves resources
because the StringBuilder class paradoxically does not create
strings, it creates StringBuilder objects. An instance of the
StringBuilder class starts with a minimum of 16 bytes of memory
and dynamically can increase of decrease this memory utilization.
You can use the Length property of the StringBuilder object
to manually change the memory allocated.
NEXT>>
|