.NET8极致性能优化Reflection

前言

反射一直是性能的瓶颈,所以无论哪个.NET版本反射的优化必然少不了。主要是集中在两个方面优化,分配和缓存。.NET8自然也不例外。本篇看下。

原文:.NET8极致性能优化Reflection

概述

比如针对GetCustomAttributes 通过反射获取属性的优化,以下例子

// dotnet run -c Release -f net7.0 --filter "*" --runtimes net7.0 net8.0public class Tests{    public object[] GetCustomAttributes() => typeof(C).GetCustomAttributes(typeof(MyAttribute), inherit: true);
    [My(Value1 = 1, Value2 = 2)]    class C { }
    [AttributeUsage(AttributeTargets.All)]    public class MyAttribute : Attribute    {        public int Value1 { get; set; }        public int Value2 { get; set; }    }}

.NET7和.NET8明显的差异,它主要是优化了避免分配一个object[1]数组来设置属性的值

方法 运行时 平均值 比率 分配 分配比率
GetCustomAttributes .NET 7.0 1,287.1 ns 1.00 296 B 1.00
GetCustomAttributes .NET 8.0 994.0 ns 0.77 232 B 0.78

其它的比如减少反射堆栈中的分配,比如通过更自由的spans。改进了Type上的泛型处理,从而提升各种与泛型相关的成员性能,比如GetGenericTypeDefinition,它的结果现在被缓存在了Type对象上​​​​​​​

// dotnet run -c Release -f net7.0 --filter "*" --runtimes net7.0 net8.0public class Tests{    private readonly Type _type = typeof(List<int>);
    public Type GetGenericTypeDefinition() => _type.GetGenericTypeDefinition();}

.NET7和.NET8如下

方法 运行时 平均值
GetGenericTypeDefinition .NET 7.0 47.426 ns 1.00
GetGenericTypeDefinition .NET 8.0 3.289 ns 0.07

都是细枝末节,影响反射性能最大的一块是MethodBase.Invoke。当在编译的时候,知道方法的签名并且通过反射来调用方法。就可以通过使用CreateDelegate来获取和缓存该方法的委托,然后通过该委托执行所有的调用。从而实现性能最佳化,但是如果在编译的时候你不知道方法的签名,则需要依赖动态的方法。比如MethodBase.Invoke,这个方法降低性能并且更耗时。一些比较了解.NET开发的人员会用 emit避免这种开销。.NET7里面采用这种方式。.NET8里面,为许多这样的情况进行了改进,以前,emitter 总是生成可以容纳 ref/out 参数的代码,但许多方法不提供这样的参数,当不需要考虑这些因素时,生成的代码可以更高效。​​​​​​​

// If you have .NET 6 installed, you can update the csproj to include a net6.0 in the target frameworks, and then run://     dotnet run -c Release -f net6.0 --filter "*" --runtimes net6.0 net7.0 net8.0// Otherwise, you can run://     dotnet run -c Release -f net7.0 --filter "*" --runtimes net7.0 net8.0
using BenchmarkDotNet.Attributes;using BenchmarkDotNet.Running;using System.Reflection;
BenchmarkSwitcher.FromAssembly(typeof(Tests).Assembly).Run(args);
[HideColumns("Error", "StdDev", "Median", "RatioSD")]public class Tests{    private MethodInfo _method0, _method1, _method2, _method3;    private readonly object[] _args1 = new object[] { 1 };    private readonly object[] _args2 = new object[] { 2, 3 };    private readonly object[] _args3 = new object[] { 4, 5, 6 };
    [GlobalSetup]    public void Setup()    {        _method0 = typeof(Tests).GetMethod("MyMethod0", BindingFlags.NonPublic | BindingFlags.Static);        _method1 = typeof(Tests).GetMethod("MyMethod1", BindingFlags.NonPublic | BindingFlags.Static);        _method2 = typeof(Tests).GetMethod("MyMethod2", BindingFlags.NonPublic | BindingFlags.Static);        _method3 = typeof(Tests).GetMethod("MyMethod3", BindingFlags.NonPublic | BindingFlags.Static);    }
    [Benchmark] public void Method0() => _method0.Invoke(null, null);    [Benchmark] public void Method1() => _method1.Invoke(null, _args1);    [Benchmark] public void Method2() => _method2.Invoke(null, _args2);    [Benchmark] public void Method3() => _method3.Invoke(null, _args3);
    private static void MyMethod0() { }    private static void MyMethod1(int arg1) { }    private static void MyMethod2(int arg1, int arg2) { }    private static void MyMethod3(int arg1, int arg2, int arg3) { }}

.NET6以及7和8的情况分别如下:

方法 运行时 平均值 比率
Method0 .NET 6.0 91.457 ns 1.00
Method0 .NET 7.0 7.205 ns 0.08
Method0 .NET 8.0 5.719 ns 0.06
Method1 .NET 6.0 132.832 ns 1.00
Method1 .NET 7.0 26.151 ns 0.20
Method1 .NET 8.0 21.602 ns 0.16
Method2 .NET 6.0 172.224 ns 1.00
Method2 .NET 7.0 37.937 ns 0.22
Method2 .NET 8.0 26.951 ns 0.16
Method3 .NET 6.0 211.247 ns 1.00
Method3 .NET 7.0 42.988 ns 0.20
Method3 .NET 8.0 34.112 ns 0.16

这里有一些问题,每次调用都会涉及到一些性能开销,每次调用都会重复。如果我们可以提取这些重复性的工作,对它们进行缓存。就可以实现更好的性能。.NET8里面通过 MethodInvoker 和 ConstructorInvoker 类型中实现了这些功能。这些并没有包含所有 MethodBase.Invoke 处理的不常见错误(如特别识别和处理 Type.Missing),但对于其他所有情况,它为优化在构建时未知签名的方法的重复调用提供了一个很好的解决方案。​​​​​​​

// dotnet run -c Release -f net8.0 --filter "*"
using BenchmarkDotNet.Attributes;using BenchmarkDotNet.Running;using System.Reflection;
BenchmarkSwitcher.FromAssembly(typeof(Tests).Assembly).Run(args);
[HideColumns("Error", "StdDev", "Median", "RatioSD")]public class Tests{    private readonly object _arg0 = 4, _arg1 = 5, _arg2 = 6;    private readonly object[] _args3 = new object[] { 4, 5, 6 };    private MethodInfo _method3;    private MethodInvoker _method3Invoker;
    [GlobalSetup]    public void Setup()    {        _method3 = typeof(Tests).GetMethod("MyMethod3", BindingFlags.NonPublic | BindingFlags.Static);        _method3Invoker = MethodInvoker.Create(_method3);    }
    [Benchmark(Baseline = true)]     public void MethodBaseInvoke() => _method3.Invoke(null, _args3);
    [Benchmark]    public void MethodInvokerInvoke() => _method3Invoker.Invoke(null, _arg0, _arg1, _arg2);
    private static void MyMethod3(int arg1, int arg2, int arg3) { }}

.NET8的情况如下

方法 平均值 比率
MethodBaseInvoke 32.42 ns 1.00
MethodInvokerInvoke 11.47 ns 0.35

这些类型被 Microsoft.Extensions.DependencyInjection.Abstractions 中的 ActivatorUtilities.CreateFactory 方法使用,以进一步提高 DI 服务构建性能。通过添加额外的缓存层进一步改进,进一步避免每次构建时的反射。

扫描二维码关注公众号,回复: 17128980 查看本文章

 

作者:jianghupt

欢迎关注公众号 (jianghupt),文章首发地。

IntelliJ IDEA 2023.3 & JetBrains 全家桶年度大版本更新 新概念“防御性编程”:让自己稳拿铁饭碗 GitHub.com 跑了 1200 多台 MySQL 主机,如何无缝升级到 8.0? 周星驰 Web3 团队下个月上线独立 App Firefox 会被淘汰吗? Visual Studio Code 1.85 发布,浮动窗口 美国 CISA 建议放弃 C/C++,消除内存安全漏洞 余承东:华为明年将推出颠覆性产品,改写行业历史 TIOBE 12 月:C# 有望成为年度编程语言 雷军 30 年前写的论文:《计算机病毒判定专家系统原理与设计》
{{o.name}}
{{m.name}}

猜你喜欢

转载自my.oschina.net/u/5407571/blog/10320411