字符串连接优化聚合 [英] Optimizing Aggregate for String Concatenation

查看:188
本文介绍了字符串连接优化聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新 - 对于那些心灵的滑稽画面,你可以假设总结仍然产生任何功能传递给它,包括在案件被优化的正常结果。

Update - for those of a facetious frame of mind, you can assume that Aggregate still produces the normal result whatever function is passed to it, including in the case being optimized.

我写了这个程序,用逗号从0到19999单独建立一个整数的长字符串。

I wrote this program to build a long string of integers from 0 to 19999 separate by commas.

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

在五秒钟可怕。当然,这是因为整个字符串是围绕循环每次被复制。

Over five seconds, terrible. Of course it's because the whole string is being copied each time around the loop.

但是,如果做一个很小的变化由有何评论?

But what if make one very small change indicated by the comment?

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");
        }
    }
}

现在,当我运行它,它说:

Now when I run it, it says:

42ms

在快100倍。

什么是在MakeAggregateGoFaster命名空间?

What's in the MakeAggregateGoFaster namespace?

更新2: 说起来我回答这里

推荐答案

您是'覆盖'System.Linq.Aggregate在命名空间$自己的扩展方法b $ b MakeAggregateGoFaster。

You are 'overriding' System.Linq.Aggregate with your own extension method in namespace MakeAggregateGoFaster.

也许专门对的IEnumerable<串> 和利用一个StringBuilder的

Perhaps specialised on IEnumerable<string> and making use of a StringBuilder?

也许服用表达式来; Func键<字符串,字符串,字符串>> ,而不是 Func键<字符串,字符串,字符串> ,因此它可以分析表达式树和编译使用,而不是直接调用该函数的StringBuilder一些代码

Maybe taking an Expression<Func<string, string, string>> instead of a Func<string, string, string> so it can analyse the expression tree and compile some code that uses StringBuilder instead of calling the function directly?

只是猜测

这篇关于字符串连接优化聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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