在 C# 中是否有任何特定的按位运算(AND、OR、XOR 等)比其他运算更快?
我问的原因是因为我知道在硬件中,大多数东西都是使用与非门构建的,因为一些与非门可以复制任何其他门。这对高级编程语言有什么影响吗?或者让它们之间的所有抽象层都以相同的速度运行。
我意识到从中获得的任何性能提升都是微乎其微的,我只是出于好奇而问。
编辑:请不要试图解释没有功能上的理由知道这一点。这实际上只是好奇心。
但是,我通过对两个数字执行一些按位运算来生成 HashCode。使用尽可能最便宜/最快的操作是有意义的。同样,这不会有任何区别,我只是好奇。
编辑:我的问题归结为:硬件依赖于较低级别的 NAND 门这一事实是否对较高级别的进程有任何影响。这会导致 NAND 比 XOR 更快吗?
出于好奇,我问硬件的细节如何影响软件。这对我来说很有趣。
Is any particular bitwise operation (AND, OR, XOR, etc.) faster than another in C#?
我创建了一个基准:
Random r = new Random();
int a = r.Next();
int b = r.Next();
int c = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < int.MaxValue; i++)
{
c += a & b;
}
sw.Stop();
Console.WriteLine("AND operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
// The above is just to make sure that the optimizer does not optimize the loop away,
// as pointed out by johnnycrash in the comments.
sw.Restart();
for (int i = 0; i < int.MaxValue; i++)
{
c += a | b;
}
sw.Stop();
Console.WriteLine("OR operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
c += a ^ b;
}
sw.Stop();
Console.WriteLine("XOR operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
c += ~a;
}
sw.Stop();
Console.WriteLine("NOT operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
c += a << 1;
}
sw.Stop();
Console.WriteLine("Left shift operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
c += a >> 1;
}
sw.Stop();
Console.WriteLine("Right shift operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
它输出这个:
AND operator: 7979680 ticks
OR operator: 7826806 ticks
XOR operator: 7826806 ticks
NOT operator: 7826806 ticks
Left shift operator: 7826806 ticks
Right shift operator: 7826806 ticks
AND 运算符需要更长的时间,因为它是第一个循环。例如,如果我切换 AND 和 OR 循环,则 OR 循环会花费更多时间。