日期:2014-04-19 浏览次数:20398 次
string s = "";
long t1 = System.DateTime.Now.Ticks;
for(int i=0;i<10000;i++)s += Convert.ToString(i);
long t2 = System.DateTime.Now.Ticks;
long t3 = System.DateTime.Now.Ticks;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for(int i=0;i<10000;i++)sb.Append(Convert.ToString(i));
string s1 = sb.ToString();
long t4 = System.DateTime.Now.Ticks;
long t5 = System.DateTime.Now.Ticks;
System.Text.StringBuilder sb1 = new System.Text.StringBuilder(5000);
for(int i=0;i<10000;i++)sb1.Append(i);
string s2 = sb1.ToString();
long t6 = System.DateTime.Now.Ticks;
long t7 = System.DateTime.Now.Ticks;
System.Text.StringBuilder sb2 = new System.Text.StringBuilder(10000);
for(int i=0;i<10000;i++)sb2.Append(i);
string s3 = sb2.ToString();
long t8 = System.DateTime.Now.Ticks;
ListViewItem item1 = result.Items.Add("使用String类,利用operator +进行操作");
item1.SubItems.Add(Convert.ToString((t2-t1)/10000));
ListViewItem item2 = result.Items.Add("使用StringBuilder类,不对初始大小赋值");
item2.SubItems.Add(Convert.ToString((t4-t3)/10000));
ListViewItem item3 = result.Items.Add("使用StringBuilder类,对初始大小赋值为申请数量的1/2");
item3.SubItems.Add(Convert.ToString((t6-t5)/10000));
ListViewItem item4 = result.Items.Add("使用StringBuilder类,对初始大小赋值为申请数量");
item4.SubItems.Add(Convert.ToString((t8-t7)/10000));
2、异常对性能的影响,当然,下面这个例子没有进行异常的分发、捕获等,所以时间不长。
int j = 0;
long t1 = System.DateTime.Now.Ticks;
for(int i = 0; i < 10000; i++)
{
try
{
j = i;
throw new System.Exception();
}
catch {}
}
long t2 = System.DateTime.Now.Ticks;
long t3 = System.DateTime.Now.Ticks;
for(int i = 0; i < 10000; i++)
{
try
{
j = i;
//throw new System.Exception();
}
catch {}
}
long t4 = System.DateTime.Now.Ticks;
result.Items.Clear();
ListViewItem item1 = result.Items.Add("抛出10000个异常");
item1.SubItems.Add(Convert.ToString((t2-t1)/10000));
ListViewItem item2 = result.Items.Add("屏蔽异常");
item2.SubItems.Add(Convert.ToString((t4-t3)/10000));
3、使用Foreach循环与使用For循环(差别较大)
string s = "monkeys!";
int dummy = 0;
System.Text.StringBuilder sb = new System.Text.StringBuilder(s);
for(int i = 0; i < 1000000; i++)sb.Append(s);
s = sb.ToString();
long t1 = System.DateTime.Now.Ticks;
foreach (char c in s) dummy++;
long t2 = System.DateTime.Now.Ticks;
dummy = 0;
long t3 = System.DateTime.Now.Ticks;
for (int i = 0; i < 1000000; i++)dummy++;
long t4 = System.DateTime.Now.Ticks;
result.Items.Clear();
ListViewItem item1 = result.Items.Add("使用foreach循环");
item1.SubItems.Add(Convert.ToString((t2-t1)/10000));
ListViewItem item2 = result.Items.Add("使用for循环");