博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
猜猜几种c#字符串连接所消耗时间的先后?
阅读量:6611 次
发布时间:2019-06-24

本文共 2772 字,大约阅读时间需要 9 分钟。

猜猜几种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));

你答对了吗?

上答案啦!

转载于:https://www.cnblogs.com/LoveLyre/archive/2011/09/02/2163535.html

你可能感兴趣的文章
Hadoop 添加删除数据节点(datanode)
查看>>
33.8. slb configuration
查看>>
ext的window如何隐藏水平滚动条
查看>>
71.8. Run level shell script to start Oracle 10g services on RedHat Enterprise Linux (RHAS 4)
查看>>
SAP QM Transfer of Inspection Stock
查看>>
全新视觉| 数治省市:SAP大数据构想一切可能
查看>>
ORACLE expdp备份与ORA-31693、ORA-02354、ORA-02149
查看>>
DBMS_STATS.GATHER_TABLE_STATS
查看>>
Java-单机版的书店管理系统(练习设计模块和思想_系列 五 )
查看>>
嵌入式 详解udev
查看>>
《C程序员:从校园到职场》出版预告(2):从“百花齐放”到“一枝独秀”
查看>>
Network Monitor 查询命令和MySQL命令
查看>>
好“戏”刚刚开幕 云计算逐步被认可
查看>>
云安全:这也是需要花大钱去建设的部分
查看>>
以全局产业观领航智慧城市建设
查看>>
5G网络不止能1秒下一部电影,它还能够…
查看>>
中国电信集采终端6700万部 金额达1070亿元
查看>>
2016年的十个数据中心故事
查看>>
《Java并发编程的艺术》一一3.3 顺序一致性
查看>>
《CCNP SWITCH 300-115认证考试指南》——导读
查看>>