它是更有效的通过转换为uint,而不是检查负值来执行一系列检查? [英] Is it more efficient to perform a range check by casting to uint instead of checking for negative values?

查看:269
本文介绍了它是更有效的通过转换为uint,而不是检查负值来执行一系列检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了这段代码在.NET中的列表源代码

I stumbled upon this piece of code in .NET's List source code:

// Following trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
  ThrowHelper.ThrowArgumentOutOfRangeException();
}



显然,这是更有效的(?)不是如果(指数℃,||索引> = _size)

我很好奇的伎俩背后的基本原理。是一个单一的分支指令确实比两次转换更昂贵的 UINT ? ?或者是有一些其他的优化​​回事,这将使该代码不是额外的数字比较快

I am curious about the rationale behind the trick. Is a single branch instruction really more expensive than two conversions to uint? Or is there some other optimization going on that will make this code faster than an additional numeric comparison?

为了解决在房间里的大象:是的,这是微优化,不,我不打算在我的代码到处使用这个 - 我只是好奇;)

推荐答案

我的分区,第12.1(支持的数据类型):

From MS Partition I, section 12.1 (Supported data types):

有符号整数类型(INT8,INT16,INT32,Int64的,和本地INT)和它们相应的无符号
整数类型(无符号的int8,无符号INT16,无符号INT32,无符号的int64和本地无符号
INT)中如何整数的比特仅解释不同。对于其中的无符号整数
是一个符号整数区别对待那些操作(例如,在比较或溢出算术)有用于治疗整数作为符号(例如,cgt.un和独立
指示add.ovf.un)。

The signed integer types (int8, int16, int32, int64, and native int) and their corresponding unsigned integer types (unsigned int8, unsigned int16, unsigned int32, unsigned int64, and native unsigned int) differ only in how the bits of the integer are interpreted. For those operations in which an unsigned integer is treated differently from a signed integer (e.g., in comparisons or arithmetic with overflow) there are separate instructions for treating an integer as unsigned (e.g., cgt.un and add.ovf.un).

也就是说,的转换从 INT UINT 仅仅是一个簿记的事 - 从现在开始,在堆栈上/在寄存器中的值现在是已知的是一个unsigned int而不是int。

That is, the conversion from an int to a uint is merely a matter of book-keeping - from now on, the value on the stack/in a register is now known to be an unsigned int rather than an int.

因此,两者的转换应该是自由一旦代码即时编译,然后可以进行无符号比较操作。

So the two conversions should be "free" once the code is JITted, and then the unsigned comparison operation can be performed.

这篇关于它是更有效的通过转换为uint,而不是检查负值来执行一系列检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆