Книга: C# 2008 Programmer
The StringBuilder Class
The StringBuilder Class
Earlier in this chapter you saw how to easily concatenate two strings by using the +
operator. That's fine if you are concatenating a small number of strings, but it is not recommended for large numbers of strings. The reason is that String
objects in .NET are immutable, which means that once a string variable is initialized, its value cannot be changed. When you concatenate another string to an existing one, you actually discard its old value and create a new string object containing the result of the concatenation. When you repeat this process several times, you incur a performance penalty as new temporary objects are created and old objects discarded.
One important application of the StringBuilder
class is its use in .NET interop with native C/C++ APIs that take string arguments and modify strings. One example of this is the Windows API function GetWindowText()
. This function has a second argument that takes a TCHAR*
parameter. To use this function from .NET code, you would need to pass a StringBuilder
object as this argument.
Consider the following example, where you concatenate all the numbers from 0 to 9999:
int counter = 9999;
string s = string.Empty;
for (int i = 0; i <= counter; i++) {
s += i.ToString();
}
Console.WriteLine(s);
At first glance, the code looks innocent enough. But let's use the Stopwatch
object to time the operation. Modify the code as shown here:
int counter = 9999;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
string s = string.Empty;
for (int i = 0; i <= counter; i++) {
s += i.ToString();
}
sw.Stop();
Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);
Console.WriteLine(s);
On average, it took about 374 ms on my computer to run this operation. Let's now use the StringBuilder
class in .NET to perform the string concatenation, using its Append()
method:
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= 9999; i++) {
sb.Append(i.ToString());
}
sw.Stop();
Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);
Console.WriteLine(sb.ToString());
On average, it took about 6 ms on my computer to perform this operation. As you can deduce, the improvement is drastic — 98% ((374-6)/374). If you increase the value of the loop variant (counter), you will find that the improvement is even more dramatic.
The StringBuilder
class represents a mutable string of characters. Its behavior is like the String
object except that its value can be modified once it has been created.
The StringBuilder
class contains some other important methods, which are described in the following table.
Method | Description |
---|---|
Append |
Appends the string representation of a specified object to the end of this instance. |
AppendFormat |
Appends a formatted string, which contains zero or more format specifiers, to this instance. Each format specification is replaced by the string representation of a corresponding object argument. |
AppendLine |
Appends the default line terminator, or a copy of a specified string and the default line terminator, to the end of this instance. |
CopyTo |
Copies the characters from a specified segment of this instance to a specified segment of a destination Char array. |
Insert |
Inserts the string representation of a specified object into this instance at a specified character position. |
Remove |
Removes the specified range of characters from this instance. |
Replace |
Replaces all occurrences of a specified character or string in this instance with another specified character or string. |
ToString |
Converts the value of a StringBuilder to a String . |
- The System.String Class
- InterBase Classic Server под Linux
- Каталог BIN в InterBase Classic Server для Linux
- Classic
- Classic vs SuperServer
- Рекомендации по выбору архитектуры: Classic или SuperServer?
- Эффективное взаимодействие процессов архитектуры Classic Server
- Yaffil Classic Server - замена InterBase Classic 4.0
- 4.4.4 The Dispatcher
- SERVER PRIORITY CLASS
- About the author
- Chapter 7. The state machine