c# - Lambda Actions 或 AggressiveInlined 以避免评估复杂的字符串并将其传递给单独的静态类?

标签 c# function inline

我试图避免评估字符串并将其传递给单独的静态类,如果该类中设置的标志无论如何都会跳过使用字符串。使用 System.Diagnostics.Stopwatch 进行基本性能测量。一个 C# .NET Framework 4.8 库,它是语音识别应用程序的插件。

该插件多次调用静态类,传递各种评估的字符串。根据该类中设置的静态状态过滤不同的调用,因此仅当匹配的静态 bool 值为 true 时才使用字符串。例如

Logger.MenuWrite(string msg) 仅当 Logger.MenuItems 为 true 时才会记录字符串。

根据秒表测量,我认为无论 Logger 类是否不会使用字符串,字符串总是会被评估(也就是说,我不认为 JIT 不是内联的)。虽然这样做的性能影响很小,但我在扩大规模时会尽力争取每一毫秒。

到目前为止我已经尝试和测试过的内容:

我在一些循环周围添加了秒表测量,这些循环在 Logger.MenuItems 为 false 时进行了大量 Logger.MenuWrite() 调用,然后使用检查测量了相同的循环对于 Logger.MenuItems,每次调用都是内联完成的,并且看到了明确的、可重复的差异 - 对于只有一个评估字段的字符串,每 1000 次调用会减少大约一毫秒。

我首先在 Logger 类中的静态方法上尝试了 [MethodImpl(MethodImplOptions.AggressiveInlined)],如下所示:

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void MenuWrite(string msg)
        {
            if (s_MenuItems )
            {   vaProxy.WriteToLog(s_Prefix + msg); }
        }

这将循环时间减少了一半,但仍然比我在循环中进行实际直接检查多大约 1/2 毫秒,例如:

if (Logger.MenuItems) { Logger.MenuWrite(msg); }

所以我尝试使用委托(delegate),如下所示:

        static Action<string> LogIfMenu = (msg) =>
        {
            if (Logger.MenuItems) { Logger.MenuWrite(msg); }
        };

但是使用 LogIfMenu 调用似乎与使用 [MethodImpl(MethodImplOptions.AggressiveInlined)] 具有相同或更差的性能。

对于导致性能命中的原因有什么想法 - 字符串评估/创建、方法调用,还是其他什么?除了手动内联所有调用之外,将不胜感激任何建议或选项。谢谢。

编辑:

  • 通过评估字符串,我的意思是提取其他数据,例如:$"Passed: {Cmd.Observable} and {Cmd.Dist}"
  • 我将尝试查看列出的其他性能工具,但确实需要测量发布版本中所花费的时间
  • 恐怕我必须使用动态对象进行日志记录,因为这是我的插件所提供的应用程序所提供的。也就是说,我不认为它是此问题的一部分,因此将其从代码片段中删除。

编辑:将小型可重现示例修改为控制台应用程序。

// File1.cs
namespace CS_Console_Test_05
{
    static public class Logger
    {
        public static bool MenuItems = false;
        public static void MenuWrite(string msg)
        {
            if (MenuItems) { Console.WriteLine(msg); }
        }
    }
}

// File2.cs
namespace CS_Console_Test_05
{
    internal class Program
    {
        public static void LoopMessagesInline()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000; i++)
            {
                if (Logger.MenuItems)
                { Logger.MenuWrite($"Counting Down to the time {sw.Elapsed}"); }
            }
            sw.Stop();
            Console.WriteLine($"Inline Elapsed = {sw.Elapsed}");
        }

        public static void LoopMessagesCall()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000; i++)
            {
                Logger.MenuWrite($"Counting Down to the time {sw.Elapsed}");
            }
            sw.Stop();
            Console.WriteLine($"Called Elapsed = {sw.Elapsed}");
        }

        static void Main(string[] args)
        {
            do
            {
                Console.WriteLine("Enter Value for MenuItems:");
                string miRead = Console.ReadLine();
                Logger.MenuItems = (miRead.Equals("Kludge"));    // so JIT won't know if true or false
                Console.WriteLine("'x' to quit, SPACE for Inline, nothing for Call, then ENTER: ");
                string way = Console.ReadLine();
                way = way.ToLower();
                if (way.Equals(" "))
                { LoopMessagesCall(); }
                else if (way.Equals("x"))
                { return; }
                else
                { LoopMessagesInline(); }

            } while (true);
        }
    }
}

调用 LoopMessageInline() 大约需要 7-8 毫秒。调用 LoopMessageCall() 的时间不到 1 毫秒。

如上所述,MethodImplOptions.AggressiveInlined 和使用 Delegates 似乎都无济于事。

最佳答案

首先使用适当的基准测试工具 - 例如 BenchmarkDotNet .

我提出了以下基准:

namespace CS_Console_Test_05
{
    static public class Logger
    {
        public static bool MenuItems = false;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void MenuWrite(string msg)
        {
            if (MenuItems)
            {
                Console.WriteLine(msg);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void MenuWriteFormattableString(FormattableString msg)
        {
            if (MenuItems)
            {
                Console.WriteLine(msg);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void MenuWriteFunc(Func<string> msg)
        {
            if (MenuItems)
            {
                Console.WriteLine(msg());
            }
        }
    }
}
[MemoryDiagnoser]
public class LoggerWrapperBench
{
    public static string Value = "TestVal";
    private const int Iterations = 1000;

    [Benchmark]
    public void LoopMessagesInline()
    {
        for (int i = 0; i < Iterations; i++)
        {
            if (Logger.MenuItems)
            {
                Console.WriteLine($"Counting Down to the time {Value}");
            }
        }
    }

    [Benchmark]
    public void LoopMessagesInlineFormatableString()
    {
        for (int i = 0; i < Iterations; i++)
        {
            Logger.MenuWriteFormattableString($"Counting Down to the time {Value}");
        }
    }
    
    [Benchmark]
    public void LoopMessagesInlineFunc()
    {
        for (int i = 0; i < Iterations; i++)
        {
            Logger.MenuWriteFunc(() => $"Counting Down to the time {Value}");
        }
    }

    [Benchmark]
    public void LoopMessagesCall()
    {
        for (int i = 0; i < Iterations; i++)
        {
            Logger.MenuWrite($"Counting Down to the time {Value}");
        }
    }
}

这在我的机器上给出:

<表类=“s-表”> <标题> 方法 平均值 错误 标准偏差 Gen0 已分配 <正文> 内联循环消息 524.7 纳秒 10.10 纳秒 10.37 纳秒 - - LoopMessagesInlineFormatableString 10,908.3 纳秒 215.37 纳秒 328.89 纳秒 10.1929 64000 B LoopMessagesInlineFunc 1,031.8 纳秒 18.34 纳秒 21.12 纳秒 - - 循环消息调用 14,523.6 纳秒 286.28 纳秒 391.86 纳秒 14.0228 88000 B

使惰性函数方法最接近内联方法(尽管我有点想知道为什么它不分配任何东西)。

请注意,在 MenuWrite 的情况下,内联对字符串计算没有太大影响。和MenuWriteFormattableString因为:

var s = DoSomething(); // like build string
if(...)
{
    Console.WriteLine(s);
}

还有

if(...)
{
    Console.WriteLine(DoSomething());
}

在一般情况下功能并不等效(由于函数调用可能产生副作用),因此内联不应改变程序的正确性,因此会调用字符串格式化(至少这是我关于该主题的理论)。

UPD

还有一种方法值得一提(尽管我无法让它执行得更快,并且在多个插值元素的情况下甚至可以执行得更慢) - 从 .NET 6 开始,您可以创建一个 custom interpolated string handler :

[InterpolatedStringHandler]
public readonly ref struct LogInterpolatedStringHandler
{
    readonly StringBuilder? _builder;

    public LogInterpolatedStringHandler(int literalLength, int formattedCount)
    {
        if (Logger.MenuItems)
        {
            _builder = new StringBuilder(literalLength);
        }
    }

    public void AppendLiteral(string s) => _builder?.Append(s);

    public void AppendFormatted<T>(T t) => _builder?.Append(t?.ToString());

    internal string GetFormattedText()
    {
        if (_builder is not null)
        {
            var format = _builder.ToString();
            Console.WriteLine(format);
            return format;
        }

        return string.Empty;
    }
}

及用法:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void MenuWriteInterpolatedStringHandler(ref LogInterpolatedStringHandler msg)
{
    if(MenuItems) msg.GetFormattedText();
}
[Benchmark]
public void LoopMenuWriteInterpolatedStringHandler()
{
    for (int i = 0; i < Iterations; i++)
    {
        Logger.MenuWriteInterpolatedStringHandler($"Counting Down to the time {Value}");
    }
}

这在我的机器上给出:

<表类=“s-表”> <标题> 方法 平均值 错误 标准偏差 已分配 <正文> LoopMenuWriteInterpolatedStringHandler 1,690.0 纳秒 32.63 纳秒 36.27 纳秒 - 内联循环消息 534.2 纳秒 10.39 纳秒 15.22 纳秒 -

关于c# - Lambda Actions 或 AggressiveInlined 以避免评估复杂的字符串并将其传递给单独的静态类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75961411/

相关文章:

c# - Winforms用户控件现象: suddenly all items are away!

java - 如何以恒定速度沿着正弦函数移动

c++ - 在调用者内部扩展被调用者的指导原则是什么(内联-编译器优化)

C++ 缩短后续函数调用

c# - 在整个 WPF 窗口上设置 KeyBinding

c# - 在 Xamarin.Android 中的 OnMeasure 覆盖方法中添加到单独的布局中时,不会呈现 TextView

C# : Out of Memory exception

javascript - 具有默认参数值的 es6 类构造函数上的 NodeJS 错误

python - 是否可以不从 python 中的函数返回任何内容?

javascript - 为什么禁止内联脚本(内容安全策略)?