猜猜几种c#字符串连接所消耗时间的先后?

猜猜几种c#字符串连接所消耗时间的先后?

1. 字符串字面值直接连加

test = "I1" + "I2" + "I3" + "I4" + "I5";

2.字符串字面值用+=相加

    test = "I6";
test
+= "I7";
test
+= "I8";
test
+= "I9";
test
+= "I10";

3.sn为字符串变量

 test = s1 + s2 + s3 + s4 + s5;

4.

   test = s1;
test
+= s2;
test
+= s3;
test
+= s4;
test
+= s5;

 

5.csn为字符串常量

 test = cs1 + cs2 + cs3 + cs4 + cs5;

6.

    test = cs1;
test
+= cs2;
test
+= cs3;
test
+= cs4;
test
+= cs5;


以上6种方式各循环10000000次,你能猜出他们执行所需时间的的顺序吗? 如果你是c++程序员,我觉得对于这个问题你可能会不占优势,你可能想到临时变量之类的吧.

看测试代码:

            const int Num = 10000000;
int end;
string test = "";

int start = Environment.TickCount;
for (int i = 0; i < Num; i++)
{
test
= "I1" + "I2" + "I3" + "I4" + "I5";
}
end
= Environment.TickCount;
Console.WriteLine(
"字符串字面值:" + (end - start));

start
= Environment.TickCount;
for (int i = 0; i < Num; i++)
{
test
= "I6";
test
+= "I7";
test
+= "I8";
test
+= "I9";
test
+= "I10";
}
end
= Environment.TickCount;
Console.WriteLine(
"字符串字面值:" + (end - start));


string s1 = "e1";
string s2 = "e2";
string s3 = "e3";
string s4 = "e4";
string s5 = "e5";

start
= Environment.TickCount;
for (int i = 0; i < Num; i++)
{
test
= s1 + s2 + s3 + s4 + s5;
}
end
= Environment.TickCount;
Console.WriteLine(
"变量:" + (end - start));

s1
= "h1";
s2
= "h2";
s3
= "h3";
s4
= "h4";
s5
= "h5";
start
= Environment.TickCount;
for (int i = 0; i < Num; i++)
{
test
= s1;
test
+= s2;
test
+= s3;
test
+= s4;
test
+= s5;
}
end
= Environment.TickCount;
Console.WriteLine(
"变量:" + (end - start));


const string cs1 = "H1";
const string cs2 = "H2";
const string cs3 = "H3";
const string cs4 = "H4";
const string cs5 = "H5";

start
= Environment.TickCount;
for (int i = 0; i < Num; i++)
{
test
= cs1 + cs2 + cs3 + cs4 + cs5;
}
end
= Environment.TickCount;
Console.WriteLine(
"字符串常量 :" + (end - start));

start
= Environment.TickCount;
for (int i = 0; i < Num; i++)
{
test
= cs1;
test
+= cs2;
test
+= cs3;
test
+= cs4;
test
+= cs5;
}
end
= Environment.TickCount;
Console.WriteLine(
"字符串常量:" + (end - start));


你答对了吗?

上答案啦!

posted @ 2011-09-02 11:33  Love Lyre  阅读(3035)  评论(24编辑  收藏  举报