C # the following code can be used to process strings:
String
StringBuilder
There are many opinions on the Internet:
1. StringBuilder processes strings faster than strings;
2. Do not use the string + operation as much as possible during programming;
3. Use StringBuilder as much as possible for large texts;
To verify these ideas, I did the following tests:
First time: Test (32-length) The + algorithm operation of short strings and comparison with StringBuilder AppendFormat
Test method: constant reassignment of a string (StringBuilder) variable;
The Code is as follows:
[Csharp]
For (int step = 0; step <3; step ++)
{
Console. WriteLine ("string 100000 plus test :");
Stopwatch sw = new Stopwatch ();
Sw. Start ();
String str_1 = string. Empty;
For (int I = 0; I <100000; I ++)
{
Str_1 = I. ToString () + Guid. NewGuid ();
}
Sw. Stop ();
Console. WriteLine ("\ t consumed time: {0}", sw. ElapsedMilliseconds );
Console. WriteLine ("StringBuilder AppendFormat 100000 test :");
Sw. Reset ();
Sw. Start ();
StringBuilder str_2 = new StringBuilder (string. Empty );
For (int I = 0; I <100000; I ++)
{
Str_2.Clear ();
Str_2.AppendFormat ("{0} {1}", I. ToString (), Guid. NewGuid ());
}
Sw. Stop ();
Console. WriteLine ("\ t consumed time: {0}", sw. ElapsedMilliseconds );
}
Running result:
Test results (in my opinion ):
1. Processing of small strings (Constant Value assignment) and string + operations are more efficient;
2. However, the implementation of the StringBuilder AppendFormat method seems to be more stable;
Second: Compare the plus algorithm operation of long strings with the AppendFormat of StringBuilder
With the first change:
The first time is to constantly assign values to the original variable, and the second time is to continuously accumulate the original variable value.
(To speed up execution, I reduced the number of cycles to 10000)
Code:
[Csharp]
For (int step = 0; step <3; step ++)
{
Console. WriteLine ("string 10000 plus test :");
Stopwatch sw = new Stopwatch ();
Sw. Start ();
String str_1 = string. Empty;
For (int I = 0; I <10000; I ++)
{
<Strong> <u> str_1 + = I. ToString () + Guid. NewGuid (); </u> </strong>
}
Sw. Stop ();
Console. WriteLine ("\ t consumed time: {0}", sw. ElapsedMilliseconds );
Console. WriteLine ("StringBuilder AppendFormat 10000 test :");
Sw. Reset ();
Sw. Start ();
StringBuilder str_2 = new StringBuilder (string. Empty );
For (int I = 0; I <10000; I ++)
{
<Strong> <u> // str_2.Clear ();
Str_2.AppendFormat ("{0} {1}", I. ToString (), Guid. NewGuid (); </u> </strong>
}
Sw. Stop ();
Console. WriteLine ("\ t consumed time: {0}", sw. ElapsedMilliseconds );
}
Running result:
Test results:
In the string connection operation, the execution efficiency of string is significantly lower than that of StringBuilder.
Author: ymchinabye