【发布时间】:2008-12-09 23:12:48
【问题描述】:
更新 - 对于那些喜欢开玩笑的人,您可以假设 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");
}
}
}
当我运行它时,它会说:
5116ms
超过五秒,太可怕了。当然这是因为每次循环都会复制整个字符串。
但是,如果根据评论做出一个非常小的更改呢?
using System;
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication5
{
using MakeAggregateGoFaster; // <---- inserted this
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");
}
}
}
现在当我运行它时,它会说:
42ms
快 100 倍以上。
问题
MakeAggregateGoFaster 命名空间中有什么?
更新 2: Wrote up my answer here.
【问题讨论】:
-
你在问什么?您是否编写了 MakeAggregateGoFaster,这是一个难题?
-
我搁置这个的原因是你给了我们一个“嘿,我是怎么让它更快的”而没有给我们代码的;造成这种情况,“我可以做十几种不同的事情来加快速度。”或者:“这是一个聪明的谜题,我希望你能解决它”——Stack Overflow 对这两件事都不好。
标签: c# optimization linq-to-objects