“Math.DivRem”与“Math.DivRem”之间的差异和 % 运算符?
System.Math.DivRem()
和 %
运算符有什么区别?
What is the difference between System.Math.DivRem()
and the %
operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可能是一种优化,但不幸的是产生与除法PLUS mod操作相同的IL。
在典型的体系结构(x86 和朋友)上,这两个可以通过单个操作获得,但 .NET JIT 似乎没有优化它(在我的测试中)。
所以下面两个是等价的:
VS:
除了后者更具可读性。
根据记录,这个丑陋的选项在 x86 和 x86 上速度更快。 x64:
希望 JIT 有一天能够改进,将两个操作优化为一个操作,因为这很简单。
It could have been an optimization, but unfortunately produces the same IL as a division PLUS a mod operation.
On typical architectures (x86 & friends) the two can be obtained from a single operation, but .NET JIT seems not to optimize that (in my tests).
So the following two are equivalent:
VS:
Except the later is more readable.
For the record this ugly option is faster on x86 & x64:
Hopefully the JIT will improve some day to optimize the two operations into a single one, since it is trivial.
%
给出除法的余数并完全丢弃商,而DivRem()
计算并返回商和余数。如果您只关心两个整数相除的余数,请使用
%
:如果您需要知道 10 除以 3 后余数为 1,请使用
DivRem()
,它返回商并将余数存储在输出参数中:%
gives you the remainder of a division and discards the quotient altogether, whileDivRem()
calculates and returns both the quotient and the remainder.If you're only concerned about the remainder of a division between two integers, use
%
:If you need to know how many times 10 was divided by 3 before having a remainder of 1, use
DivRem()
, which returns the quotient and stores the remainder in an out parameter:这是一种优化。一些处理器能够同时计算这两个值。其他处理器无法在硬件中进行划分(并且必须使用非常慢的软件例程)。
无论哪种情况(除非您有智能编译器),您最终都可能会计算相同的除法两次。由于除法在任何处理器上都不是很快(即使在硬件中实现),因此使用 Math.DivRem 可以为 JIT 提供一个很好的“提示”,使其仅计算一次值。
iirc Mono 没有实现这种优化,我什至不确定 MS 是否实现了。
It is an optimization. Some processors are able to compute both values at the same time. Other processors can't divide in hardware (and must use, very slow, software routines).
In either case (unless you have a smart compiler) you can end up computing the same division twice. Since divisions are never fast, on any processor (even when implemented in hardware), then using Math.DivRem gives the JIT a nice 'hint' to compute the values only once.
iirc Mono does not implement this optimization, and I'm not even sure if MS does.