StringBuilder初始长度很重要

和别人打赌的,今晚测试。只有代码和截图

 

代码
   
     
class Program
{
static void Main( string [] args)
{
Stopwatch watch
= new Stopwatch();

watch.Reset();
watch.Start();

StrBuilderWithInitialLength();
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
watch.Reset();
watch.Start();
StrBuilderWithoutInitialLength();
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);

}


static void StrBuilderWithInitialLength()
{
StringBuilder sb
= new StringBuilder( 80000000 );
for ( int i = 0 ; i < 40000000 ; i ++ )
{
sb.Append(
" 12 " );
}
}

static void StrBuilderWithoutInitialLength()
{
StringBuilder sb
= new StringBuilder();
for ( int i = 0 ; i < 40000000 ; i ++ )
{
sb.Append(
" 12 " );
}
}
}

运行时间截图:

StringBuilder初始长度很重要

你可能感兴趣的:(StringBuilder)