连接字符串时,C#中的for循环为什么这么慢?
我编写了一个程序,该程序在C ++和C#中都运行一个简单的for循环,但是同一件事在C#中花费的时间明显更长,为什么?我没有在考试中说明什么吗?
I wrote a program that runs a simple for loop in both C++ and C#, yet the same thing takes dramatically longer in C#, why is that? Did I fail to account for something in my test?
C#(13.95s)
C# (13.95s)
static double timeStamp() {
return (double)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
static void Main(string[] args) {
double timeStart = timeStamp();
string f = "";
for(int i=0; i<100000; i++) {
f += "Sample";
}
double timeEnd = timeStamp();
double timeDelta = timeEnd - timeStart;
Console.WriteLine(timeDelta.ToString());
Console.Read();
}
C ++(0.20s)
C++ (0.20s)
long int timeStampMS() {
milliseconds ms = duration_cast<milliseconds> (system_clock::now().time_since_epoch());
return ms.count();
}
int main() {
long int timeBegin = timeStampMS();
string test = "";
for (int i = 0; i < 100000; i++) {
test += "Sample";
}
long int timeEnd = timeStampMS();
long double delta = timeEnd - timeBegin;
cout << to_string(delta) << endl;
cin.get();
}
在我的PC上,将代码更改为使用StringBuilder
并最终转换为String
,执行时间从26.15秒减少到0.0012秒,或快20,000倍以上.
On my PC, changing the code to use StringBuilder
and converting to a String
at the end, the execution time went from 26.15 seconds to 0.0012 seconds, or over 20,000 times faster.
var fb = new StringBuilder();
for (int i = 0; i < 100000; ++i) {
fb.Append("Sample");
}
var f = fb.ToString();
如.Net文档中所述, StringBuilder
类是可变的字符串对象,与String
类相对应,该对象是一个不可变的对象,当您对字符串进行许多更改时,该对象非常有用.每次您创建新对象时将两个String
连接在一起.因为StringBuilder
的实现是字符数组的链接列表,并且新块被添加到一次8000个字符,
As explained in the .Net documentation, the StringBuilder
class is a mutable string object that is useful for when you are making many changes to a string, as opposed to the String
class, which is an immutable object that requires a new object creation every time you e.g. concatenate two String
s together. Because the implementation of StringBuilder
is a linked list of character arrays, and new blocks are added up to 8000 characters at a time, StringBuilder.Append
is much faster.