gpt4 book ai didi

c# - 性能字节 [] 到通用

转载 作者:行者123 更新时间:2023-11-30 14:09:00 29 4
gpt4 key购买 nike

我需要制作一个 byte[] -> T 扩展方法并且需要它快(不需要它很漂亮)

在绝对性能关键的环境中,此函数将在非常短的连续时间内被调用 100 次或 1000 次。

我们目前正在“滴答”级别进行优化,每个滴答都会在调用堆栈中转化为几毫秒,因此需要原始速度而不是可维护性(不是我喜欢的软件设计方式,但背后的原因是< strong>超出范围)。

考虑以下代码,它干净且可维护,但速度相对较慢(可能是由于装箱和拆箱),是否可以优化它以使其更快?

public static T ConvertTo<T>(this byte[] bytes, int offset = 0)
{
var type = typeof(T);
if (type == typeof(sbyte)) return bytes[offset].As<T>();
if (type == typeof(byte)) return bytes[offset].As<T>();
if (type == typeof(short)) return BitConverter.ToInt16(bytes, offset).As<T>();
if (type == typeof(ushort)) return BitConverter.ToUInt32(bytes, offset).As<T>();
if (type == typeof(int)) return BitConverter.ToInt32(bytes, offset).As<T>();
if (type == typeof(uint)) return BitConverter.ToUInt32(bytes, offset).As<T>();
if (type == typeof(long)) return BitConverter.ToInt64(bytes, offset).As<T>();
if (type == typeof(ulong)) return BitConverter.ToUInt64(bytes, offset).As<T>();

throw new NotImplementedException();
}

public static T As<T>(this object o)
{
return (T)o;
}

最佳答案

我也需要这个,我发现使用指针和不安全代码可以更快地完成到这些基本类型的转换。喜欢:

public unsafe int ToInt(byte[] bytes, int offset)
{
fixed(byte* ptr = bytes)
{
return *(int*)(ptr + offset);
}
}

但遗憾的是 C# 不支持泛型指针类型,所以我不得不在 IL 中编写这段代码,它不太关心泛型约束:

.method public hidebysig static !!T  Read<T>(void* ptr) cil managed
{
.maxstack 8
nop
ldarg.0
ldobj !!T
ret
}

它不是很漂亮,但它似乎适用于我的情况。使用此方法时要小心 - 您可以将任何类型作为参数传递,我不知道它会做什么。

您可以在 github 上找到整个 il 文件或下载编译好的程序集 https://github.com/exyi/RaptorDB-Document/blob/master/GenericPointerHelpers/GenericPointerHelpers.dll?raw=true我在那里有几个 helper 。

编辑:我忘了写如何使用这个方法。假设你像我一样在 GenericPointerHelper 类中编译了方法,你可以实现你的 ConvertTo 方法有点类似于我的 ToInt:

public unsafe T ConvertTo<T>(byte[] bytes, int offset)
where T: struct // not needed to work, just to eliminate some errors
{
fixed(byte* ptr = bytes)
{
return GenericPointerHelper.Read<T>(ptr + offset);
}
}

关于c# - 性能字节 [] 到通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32154478/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com