C# 中最快的 UInt32 到 int 转换
我有一个快速位级例程,可以计算值并返回 UInt32。我需要将此值存储在 SQL Server 中的 32 位 int 字段中。我不想增加字段的大小,只想将此函数的“字节”存储在 int 字段中。
一次请求数百条记录,因此我需要以最快的方式在循环中将 UInt32 转换为 int。如果最左边的位在 UInt32 中设置,它应该设置 int 的符号位(或者做任何“可重复”的事情,实际上,但符号位可能是最简单的)。
换句话说,我只想将 UInt32 的 4 个字节变成 32 位 int 的 4 个字节。我可以使用 BitConverter 类,但我不确定这是最快的方法。在像这样的未经检查的区域中执行此操作会更快吗:
UInt32 fld = 4292515959;
unchecked {
return (int)fld;
// -2451337
}
我看到这里已经提出了相反的问题,只是想知道答案是否会以其他方式相同:
I have a fast bit-level routine that calculates a value, and returns a UInt32. I need to store this value in SQL Server in a 32 bit int field. I don't want to increase the size of the field, and just want to store the "bytes" from this function the int field.
Hundreds of these records are requested at a time, so I need the fastest way to convert a UInt32 to int in a loop. If the left-most bit is set in the UInt32, it should set the sign bit of the int (or do anything "repeatable", really, but the sign bit would probably be easiest).
In other words, I just want the 4 bytes of a UInt32 to become the 4 bytes of an 32 bit int. I could use the BitConverter class, but I'm not sure that's the fastest way. Would it be faster to do this with an unchecked area like this:
UInt32 fld = 4292515959;
unchecked {
return (int)fld;
// -2451337
}
I see the reverse question has been asked here, and was just wondering if the answer would be the same going the other way:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说未经检查的版本(如
unchecked((int)x)
)是最快的方法,因为没有方法调用。我不相信有更快的方法。顺便说一句,
UInt32
只是uint
的另一个名称...就性能而言,采用一种方式与采用另一种方式相同,因此这实际上与您发布的链接。编辑:我记得亲眼观察过一个基准测试实例,其中
检查
比未检查
更快(不,这不是调试构建,这是一个经过优化的发布构建)。我不知道为什么会发生这种情况,但无论如何,不要认为通过关闭溢出检查你会获得任何可衡量的东西。I'd say the unchecked version (like
unchecked((int)x)
) is the fastest way, since there's no method call. I don't believe there's a faster way.By the way,
UInt32
is just another name foruint
... going one way is the same as going another way in terms of performance, so this is really the same as the link you posted.Edit: I remember observing first-hand an instance of a benchmark where
checked
was faster thanunchecked
(and no, it wasn't a debug build, it was a release build with optimizations). I don't know why that happened, but in any case, don't think that you'll gain anything measurable by turning of overflow checking.仅需要
unchecked((int)x)
强制转换 const,并且检查和未检查会产生相同的结果(如果代码可以编译)。例如,此代码
产生此输出
为了更简洁,此代码可以编译(与
unchecked((int)data)
相同的结果)此代码(注意 const)无法编译(需要未选中)
此代码也无法编译(需要未选中)
unchecked((int)x)
is required only casting consts and checked and unchecked produces the same results (if the code can compile).For example this code
produces this output
To be more concise, this code can be compiled (same result as
unchecked((int)data)
)This code (note the const) can't be compiled (requires unchecked)
This code can't be compiled as well (requires unchecked)