A small test,
According to beautyispower's original Code : Using System;
Using System. text;
Namespace Test
{
Public Class Testapp
{
Public Static Void Main ( String [] ARGs)
{
Int Inttimeused = 0 ;
Int Intcount = 0 ;
Int Intmaxcount = 50000 ;
String Strtest = String . Empty;
Stringbuilder sbtest = New Stringbuilder (intmaxcount );
Console. writeline ( " Adding strings using stringbuilder. " );
Inttimeused = Environment. tickcount;
While (Intcount < Intmaxcount)
{
Intcount++;
Sbtest. append ("A");
}
Inttimeused = Environment. tickcount - Inttimeused;
Console. writeline ( " End with stringbuilder to add strings. " );
Console. writeline ( " Time: {0} milliseconds " , Inttimeused );
Intcount = 0 ;
Console. writeline ( " Start to use string to add strings. " );
Inttimeused = Environment. tickcount;
While (Intcount < Intmaxcount)
{
Intcount++;
Strtest+ ="A";
}
Inttimeused = Environment. tickcount - Inttimeused;
Console. writeline ( " End with string for string addition. " );
Console. writeline ( " Time: {0} milliseconds " , Inttimeused );
}
}
}
Stringbuilder is 0 ms, and string is about 5500 Ms
Change strtest + = "A"; in the original code to strtest = string. Intern (strtest) + "";
Stringbuilder seems to be slowing down. Sometimes it is 0 ms, sometimes it is 15-16 ms,
The string is faster and stable at around 2260.
I am not very clear about the reasons. Please analyze and guide me.
Note: This article references the code of beautyispower in stringbuilder string comparison.