相关疑难解决方法(0)

优化字符串连接的聚合

更新 - 对于一个有思想的心态,你可以假设Aggregate仍会产生正常的结果,无论函数传递给它,包括在优化的情况下.

我编写了这个程序来构建一个从逗号分隔的0到19999之间的长整数字符串.

using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            const int size = 20000;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
            stopwatch.Stop();

            Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它说:

5116ms
Run Code Online (Sandbox Code Playgroud)

超过五秒钟,太可怕了.当然这是因为每次循环都会复制整个字符串.

但是,如果评论中指出了一个非常小的变化呢?

using System;
using System.Linq;
using System.Diagnostics;

namespace ConsoleApplication5
{
    using MakeAggregateGoFaster;  // <---- inserted this

    class Program
    {
        static void Main(string[] args)
        {
            const int …
Run Code Online (Sandbox Code Playgroud)

c# optimization linq-to-objects

18
推荐指数
4
解决办法
2万
查看次数

标签 统计

c# ×1

linq-to-objects ×1

optimization ×1