连接字符串时,C#中的for循环为什么这么慢? [英] How come for loops in C# are so slow when concatenating strings?

查看:366
本文介绍了连接字符串时,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 Strings 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.

这篇关于连接字符串时,C#中的for循环为什么这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆