所以我正在研究这个问题,普遍的共识是uint cast版本比0的范围检查更有效.由于代码也在MS的List实现中,我认为它是一个真正的优化.但是,我无法生成代码示例,从而为uint版本带来更好的性能.我尝试了不同的测试,但是我的代码中缺少某些东西,或者我的代码的其他部分使检查的时间相形见绌.我的最后一次尝试是这样的:
class TestType
{
public TestType(int size)
{
MaxSize = size;
Random rand = new Random(100);
for (int i = 0; i < MaxIterations; i++)
{
indexes[i] = rand.Next(0, MaxSize);
}
}
public const int MaxIterations = 10000000;
private int MaxSize;
private int[] indexes = new int[MaxIterations];
public void Test()
{
var timer = new Stopwatch();
int inRange = 0;
int outOfRange = 0;
timer.Start();
for (int i = 0; i < MaxIterations; i++)
{
int x …Run Code Online (Sandbox Code Playgroud)