【问题标题】:How to optimize and pre-compile this LINQ expression?如何优化和预编译这个 LINQ 表达式?
【发布时间】:2010-10-14 12:12:23
【问题描述】:

鉴于以下针对60% toleration 的输入

"STACKOVERflow is a quesTions and ANSwers weBSITE"

我希望得到以下输出

// Extra spaces just to show %s
// 69%          50%  100%  22%!      33% 42%     14%
"Stackoverflow  Is   A     QuesTions And ANSwers Website"

QuestionsAnswers 具有大写字符,但它们代表的字符串少于 60%,因此应保留。然后我想将每个字符串的第一个字符转换为大写。

我目前正在使用这种方法

public static class StringExtender
{
    public static string ToTitleCase(this string str, double preserve)
    {
        return String.Join(" ",
            str.Split(' ')
            .Select(x => (x.Count(y => y.ToString() == y.ToString().ToUpper()) / (double)x.Length * 100) > preserve ? x.ToLower() : x)
            .Select(x =>
                String.Join(String.Empty,
                    x.Select((y, z) => z == 0 ? y.ToString().ToUpper() : y.ToString()).ToArray()
                )
            ).ToArray()
        );
    }
}

第一次运行时,我得到15000 滴答声 (Stopwatch.EllapsedTicks),下一次运行在 300。它似乎是第一次进行某种编译...

  • 有什么方法可以不在运行时编译它,所以它第一次运行时会像下一次一样全速运行?
  • 有没有办法进一步优化这段代码?

完整代码(包括测量方法)

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

public static class StopwatchExtender
{
    public static void Timer(this Stopwatch sw, Action x, int iterations, string name)
    {
        sw.Start();
        for (int i = 0; i < iterations; ++i)
        {
            x();
        }
        sw.Stop();

        Console.WriteLine("Name: {0}\nTicks: {1}\n", name, sw.ElapsedTicks);

        sw.Reset();
    }
}

public static class StringExtender
{
    public static string OP(this string str, double preserve)
    {
        return String.Join(" ",
            str.Split(' ')
            .Select(x => (x.Count(y => y.ToString() == y.ToString().ToUpper()) / (double)x.Length * 100) > preserve ? x.ToLower() : x)
            .Select(x =>
                String.Join(String.Empty,
                    x.Select((y, z) => z == 0 ? y.ToString().ToUpper() : y.ToString()).ToArray()
                )
            ).ToArray()
        );
    }

    public static string A01(this string str, double preserve)
    {
        return string.Join(" ",
            str.Split(' ')
                .Select(s => char.ToUpper(s[0]) + ((s.Count(c => char.IsUpper(c)) / (double)s.Length * 100) > preserve ? s.Substring(1).ToLower() : s.Substring(1)))
                .ToArray()
            );
    }
}

public class Program
{
    static void Main()
    {
        var sw = new Stopwatch();

        var str = "STACKOVERflow is a quesTions and ANSwers weBSITE";

        sw.Timer(() =>
        {
            str.OP(60);
            str.A01(60);
        }, 1, "Starup takes more time");

        sw.Timer(() =>
        {
            str.OP(60);
        }, 1000000, "OP solution");

        sw.Timer(() =>
        {
            str.A01(60);
        }, 1000000, "LukeH's answer");

        Console.ReadLine();
    }
}

结果

【问题讨论】:

  • 如果只运行一次迭代,您将无法获得准确的计时。您应该运行它数万或数百万次。

标签: c# linq optimization


【解决方案1】:
public static string ToTitleCase(this string str, double preserve)
{
    return string.Join(" ",
        str.Split(' ')
           .Select(s => s.Length == 0 ? s : char.ToUpper(s[0]) + ((s.Count(c => char.IsUpper(c)) / (double)s.Length * 100) > preserve ? s.Substring(1).ToLower() : s.Substring(1)))
           .ToArray());
}

(如果您使用的是 .NET 4,请不要忘记删除最后的 ToArray 调用。)

【讨论】:

  • 更糟糕的是,我得到了3000 滴答声(在第一次之后)。我的方法在第一次后以300 滴答运行。
  • @Bruno:真的吗?在我的测试中,它的运行速度比您的版本快 4 倍(即使我添加了额外的检查以阻止它在空字符串上崩溃)。
  • @Luke:你的测试怎么样?我已经发布了我的完整代码,其中显示了 Stopwatch with lambda stackoverflow.com/questions/232848/… 的实现
  • @Luke:哎呀,我的错误,我没有改变我的方法,我已经在first time run的问题中内联测试了它。对不起。感谢您的代码。
  • @Bruno:这几乎可以肯定是因为抖动正在编译首次使用的方法。这对你来说真的是个问题吗?如果是这样,您可以考虑在应用程序启动时调用该方法一次,然后将其触发。或者看看 NGen:msdn.microsoft.com/en-us/library/6t9t5wcf.aspx
【解决方案2】:

这并没有真正回答您的问题,但 TitleCase() 方法已经在 .NET Framework 中使用了一段时间...查看 TextInfo 类:http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

【讨论】:

  • 对于字符串TITLECASEIT 它不起作用。对于tITLEcaseit,它将降低所有内容并将第一个字母大写。所以简而言之,我猜这个方法对我来说没用,除非容差是0%
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
相关资源
最近更新 更多