c# - 有没有办法将通用枚举值转换为 UInt64 值而不进行分配?

标签 c# performance memory enums garbage-collection

我想要一种快速通用的方法来检查是否用 FlagsAttribute 标记的枚举值已验证。为此,我创建了一个名为 EnumInfo<T> 的类通过按位或运算枚举的所有不同值来计算其静态构造函数中的标志模式。 IsValidFlagsValue然后,方法通过与标志模式执行按位 AND 比较来简单地检查提供的值。

考虑以下 C# 代码

// This code requires C# 7.3
public static class EnumInfo<T> where T : Enum, IConvertible
{
    // This field is calculated in the static constructor
    public static readonly ulong FlagsPattern; 

    public static bool IsValidFlagsValue(this T enumValue)
    {
        // The actual problem is here: ToUInt64 allocates (because of internal boxing?)
        var convertedUInt64Value = enumValue.ToUInt64(null);
        return (FlagsPattern & convertedUInt64Value) == convertedUInt64Value;
    }
}

我的实际问题如下:为了重用此代码,我将枚举值转换为类型 ulong 。然而,enumValue.ToUInt64(null)内部分配 24 字节,如以下基准测试所示(使用 BenchmarkDotNet 执行):

public class ToUInt64Benchmark
{
    public IConvertible FlagsValue = 
        BindingFlags.Public | BindingFlags.Instance;

    [Benchmark]
    public ulong EnumToUInt64() => FlagsValue.ToUInt64(null);
}

BenchmarkDotNet results

目前有什么方法可以避免这种分配吗?我尝试使用不安全的代码,但无法获取通用值的地址(即 &enumValue 不起作用)。是否有另一种我没有想到的方法可以做到这一点?

感谢您提前提供的帮助。

最佳答案

pinkfloydx33在这个问题的评论中指出,System.Runtime.CompilerServices.Unsafe中有一个名为Unsafe的类NuGet 包。有了它,您可以以不分配的不安全方式强制转换为 ulong。如果我们修改我的问题中的基准类,如下所示:

public class ToUInt64Benchmark
{
    public BindingFlags FlagsValue = BindingFlags.Public | BindingFlags.Instance;

    public IConvertible FlagsValueAsConvertible;

    public ToUInt64Benchmark() => FlagsValueAsConvertible = FlagsValue;

    [Benchmark(Baseline = true)]
    public ulong EnumToUInt64() => FlagsValueAsConvertible.ToUInt64(null);

    [Benchmark]
    public ulong UnsafeEnumToUInt64() => ConvertUnsafe(FlagsValue);

    private static unsafe ulong ConvertUnsafe<T>(T enumValue) where T : struct, Enum
    {
        var pointer = (ulong*)Unsafe.AsPointer(ref enumValue);
        return *pointer;
    }
}

...这会导致以下结果:

Benchmark Results with unsafe code

它的速度更快(只有 Surface Pro 4 上 .NET Core 2.2 中 ToUInt64 执行时间的 10%),而且最重要的是,它不进行分配。

请务必将 AllowUnsafeBlocks 标记添加到您的 csproj 文件中,以允许编译不安全代码。您无法在部分受信任的平台(例如 Silverlight)上运行此代码。这是我的 csproj 文件的结构。

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.2;net472</TargetFrameworks>
    <DebugType>portable</DebugType>
    <PlatformTarget>x64</PlatformTarget>
    <LangVersion>7.3</LangVersion>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.11.3" />
    <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.5.2" />
  </ItemGroup>
</Project>

更新时间 2018-12-26 17:00 UTC

pinkfloydx33在评论中正确指出(再次),可以使用 Unsafe.As 简化代码:

public class ToUInt64Benchmark
{
    // Other members omitted for brevity's sake
    [Benchmark]
    public ulong UnsafeEnumToUInt64() => ConvertUnsafe(FlagsValue);

    private static ulong ConvertUnsafe<T>(T enumValue) where T : struct, Enum => 
        Unsafe.As<T, ulong>(ref enumValue);
}

这对性能没有影响,但不需要 csproj 文件中的 AllowUnsafeBlocks 标记。

关于c# - 有没有办法将通用枚举值转换为 UInt64 值而不进行分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53929018/

相关文章:

memory - K8S容器是否使用主机操作系统的文件缓存

c# - 如何更新 Entity Framework Core 中修改的列?

java - 在两个列表中查找额外对象的最佳方法

c# - Log4Net 新事件日志不起作用

javascript - 针对常量求值的 Angular 表达式

mysql - 在将其分解为多个表之前,MySQL 表应该有多大?

c++ - 为什么删除分配的数组会导致内存错误?

c++ - 一个非内联非虚方法给一个类的实例增加了多少字节? C++

c# - 删除整个方法的命令?

c# - Curl - 获取包含图像和 css 的页面