use*_*613 245 c# performance conditional-operator
我读的是无处不在三元运营商应该是比快,或至少一样的,它的等效if
- else
块.
但是,我做了以下测试,发现事实并非如此:
Random r = new Random();
int[] array = new int[20000000];
for(int i = 0; i < array.Length; i++)
{
array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);
long value = 0;
DateTime begin = DateTime.UtcNow;
foreach (int i in array)
{
if (i > 0)
{
value += 2;
}
else
{
value += 3;
}
// if-else block above takes on average 85 ms
// OR I can use a ternary operator:
// value += i > 0 ? 2 : 3; // takes 157 ms
}
DateTime end = DateTime.UtcNow;
MessageBox.Show("Measured time: " + (end-begin).TotalMilliseconds + " ms.\r\nResult = " + value.ToString());
Run Code Online (Sandbox Code Playgroud)
我的电脑花了85毫秒来运行上面的代码.但是如果我注释掉if
- else
块,并取消注释三元运算符行,它将需要大约157毫秒.
为什么会这样?
Sam*_*ell 373
为了回答这个问题,我们将检查X86和X64 JIT为每种情况生成的汇编代码.
32: foreach (int i in array)
0000007c 33 D2 xor edx,edx
0000007e 83 7E 04 00 cmp dword ptr [esi+4],0
00000082 7E 1C jle 000000A0
00000084 8B 44 96 08 mov eax,dword ptr [esi+edx*4+8]
33: {
34: if (i > 0)
00000088 85 C0 test eax,eax
0000008a 7E 08 jle 00000094
35: {
36: value += 2;
0000008c 83 C3 02 add ebx,2
0000008f 83 D7 00 adc edi,0
00000092 EB 06 jmp 0000009A
37: }
38: else
39: {
40: value += 3;
00000094 83 C3 03 add ebx,3
00000097 83 D7 00 adc edi,0
0000009a 42 inc edx
32: foreach (int i in array)
0000009b 39 56 04 cmp dword ptr [esi+4],edx
0000009e 7F E4 jg 00000084
30: for (int x = 0; x < iterations; x++)
000000a0 41 inc ecx
000000a1 3B 4D F0 cmp ecx,dword ptr [ebp-10h]
000000a4 7C D6 jl 0000007C
Run Code Online (Sandbox Code Playgroud)
59: foreach (int i in array)
00000075 33 F6 xor esi,esi
00000077 83 7F 04 00 cmp dword ptr [edi+4],0
0000007b 7E 2D jle 000000AA
0000007d 8B 44 B7 08 mov eax,dword ptr [edi+esi*4+8]
60: {
61: value += i > 0 ? 2 : 3;
00000081 85 C0 test eax,eax
00000083 7F 07 jg 0000008C
00000085 BA 03 00 00 00 mov edx,3
0000008a EB 05 jmp 00000091
0000008c BA 02 00 00 00 mov edx,2
00000091 8B C3 mov eax,ebx
00000093 8B 4D EC mov ecx,dword ptr [ebp-14h]
00000096 8B DA mov ebx,edx
00000098 C1 FB 1F sar ebx,1Fh
0000009b 03 C2 add eax,edx
0000009d 13 CB adc ecx,ebx
0000009f 89 4D EC mov dword ptr [ebp-14h],ecx
000000a2 8B D8 mov ebx,eax
000000a4 46 inc esi
59: foreach (int i in array)
000000a5 39 77 04 cmp dword ptr [edi+4],esi
000000a8 7F D3 jg 0000007D
57: for (int x = 0; x < iterations; x++)
000000aa FF 45 E4 inc dword ptr [ebp-1Ch]
000000ad 8B 45 E4 mov eax,dword ptr [ebp-1Ch]
000000b0 3B 45 F0 cmp eax,dword ptr [ebp-10h]
000000b3 7C C0 jl 00000075
Run Code Online (Sandbox Code Playgroud)
32: foreach (int i in array)
00000059 4C 8B 4F 08 mov r9,qword ptr [rdi+8]
0000005d 0F 1F 00 nop dword ptr [rax]
00000060 45 85 C9 test r9d,r9d
00000063 7E 2B jle 0000000000000090
00000065 33 D2 xor edx,edx
00000067 45 33 C0 xor r8d,r8d
0000006a 4C 8B 57 08 mov r10,qword ptr [rdi+8]
0000006e 66 90 xchg ax,ax
00000070 42 8B 44 07 10 mov eax,dword ptr [rdi+r8+10h]
33: {
34: if (i > 0)
00000075 85 C0 test eax,eax
00000077 7E 07 jle 0000000000000080
35: {
36: value += 2;
00000079 48 83 C5 02 add rbp,2
0000007d EB 05 jmp 0000000000000084
0000007f 90 nop
37: }
38: else
39: {
40: value += 3;
00000080 48 83 C5 03 add rbp,3
00000084 FF C2 inc edx
00000086 49 83 C0 04 add r8,4
32: foreach (int i in array)
0000008a 41 3B D2 cmp edx,r10d
0000008d 7C E1 jl 0000000000000070
0000008f 90 nop
30: for (int x = 0; x < iterations; x++)
00000090 FF C1 inc ecx
00000092 41 3B CC cmp ecx,r12d
00000095 7C C9 jl 0000000000000060
Run Code Online (Sandbox Code Playgroud)
59: foreach (int i in array)
00000044 4C 8B 4F 08 mov r9,qword ptr [rdi+8]
00000048 45 85 C9 test r9d,r9d
0000004b 7E 2F jle 000000000000007C
0000004d 45 33 C0 xor r8d,r8d
00000050 33 D2 xor edx,edx
00000052 4C 8B 57 08 mov r10,qword ptr [rdi+8]
00000056 8B 44 17 10 mov eax,dword ptr [rdi+rdx+10h]
60: {
61: value += i > 0 ? 2 : 3;
0000005a 85 C0 test eax,eax
0000005c 7F 07 jg 0000000000000065
0000005e B8 03 00 00 00 mov eax,3
00000063 EB 05 jmp 000000000000006A
00000065 B8 02 00 00 00 mov eax,2
0000006a 48 63 C0 movsxd rax,eax
0000006d 4C 03 E0 add r12,rax
00000070 41 FF C0 inc r8d
00000073 48 83 C2 04 add rdx,4
59: foreach (int i in array)
00000077 45 3B C2 cmp r8d,r10d
0000007a 7C DA jl 0000000000000056
57: for (int x = 0; x < iterations; x++)
0000007c FF C1 inc ecx
0000007e 3B CD cmp ecx,ebp
00000080 7C C6 jl 0000000000000048
Run Code Online (Sandbox Code Playgroud)
第一:为什么是X86码了这么多慢于X64?
这是由于代码的以下特征:
i
数组加载之外的寄存器来执行内部循环,而X86 JIT在循环中放置了几个堆栈操作(内存访问).value
是一个64位整数,在X86上需要2个机器指令(add
后跟adc
),但在X64(add
)上只需要1个.第二:为什么X86和X64上的三元运算符速度较慢?
这是由于影响JIT优化器的操作顺序的细微差别.要JIT三元运算符,而不是直接编码2
并3
在add
机器指令本身中,JIT创建一个中间变量(在寄存器中)来保存结果.然后,在将该寄存器添加到该寄存器之前,该寄存器将从32位符号扩展到64位value
.由于所有这些都在X64的寄存器中执行,尽管三元运算符的复杂性显着增加,但净影响在某种程度上最小化.
另一方面,X86 JIT受到更大程度的影响,因为在内部循环中添加新的中间值会导致它"溢出"另一个值,导致内部循环中至少有2次额外的内存访问(请参阅访问到[ebp-14h]
在X86三元代码).
Jon*_*eet 63
编辑:所有变化......见下文.
我无法在x64 CLR上重现您的结果,但我可以在x86 上重现.在x64上,我可以看到条件运算符和if/else之间的差异很小(小于10%),但它比你看到的要小得多.
我做了以下潜在的改变:
/o+ /debug-
,并在调试器外部运行Stopwatch
结果/platform:x64
(没有"忽略"行):
if/else with 1 iterations: 17ms
conditional with 1 iterations: 19ms
if/else with 1000 iterations: 17875ms
conditional with 1000 iterations: 19089ms
Run Code Online (Sandbox Code Playgroud)
结果/platform:x86
(没有"忽略"行):
if/else with 1 iterations: 18ms
conditional with 1 iterations: 49ms
if/else with 1000 iterations: 17901ms
conditional with 1000 iterations: 47710ms
Run Code Online (Sandbox Code Playgroud)
我的系统详情:
所以不像以前,我觉得你是看到一个真正的区别-这一切都做与x86 JIT.我不想说究竟是什么原因造成的差异-我可以用更多的细节稍后更新帖子,如果我能懒得去Cordbg中进:)
有趣的是,如果不首先对数组进行排序,我最终会得到大约4.5倍的测试,至少在x64上.我的猜测是这与分支预测有关.
码:
using System;
using System.Diagnostics;
class Test
{
static void Main()
{
Random r = new Random(0);
int[] array = new int[20000000];
for(int i = 0; i < array.Length; i++)
{
array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);
// JIT everything...
RunIfElse(array, 1);
RunConditional(array, 1);
// Now really time it
RunIfElse(array, 1000);
RunConditional(array, 1000);
}
static void RunIfElse(int[] array, int iterations)
{
long value = 0;
Stopwatch sw = Stopwatch.StartNew();
for (int x = 0; x < iterations; x++)
{
foreach (int i in array)
{
if (i > 0)
{
value += 2;
}
else
{
value += 3;
}
}
}
sw.Stop();
Console.WriteLine("if/else with {0} iterations: {1}ms",
iterations,
sw.ElapsedMilliseconds);
// Just to avoid optimizing everything away
Console.WriteLine("Value (ignore): {0}", value);
}
static void RunConditional(int[] array, int iterations)
{
long value = 0;
Stopwatch sw = Stopwatch.StartNew();
for (int x = 0; x < iterations; x++)
{
foreach (int i in array)
{
value += i > 0 ? 2 : 3;
}
}
sw.Stop();
Console.WriteLine("conditional with {0} iterations: {1}ms",
iterations,
sw.ElapsedMilliseconds);
// Just to avoid optimizing everything away
Console.WriteLine("Value (ignore): {0}", value);
}
}
Run Code Online (Sandbox Code Playgroud)
Ere*_*mez 43
差异确实与if/else vs ternary没什么关系.
看看这个jitted disassemblies(我不会在这里重新讨论,请参阅@ 280Z28的回答),结果发现你正在比较苹果和橘子.在一种情况下,您+=
使用常量值创建两个不同的操作,您选择哪个操作取决于条件,而在另一种情况下,您创建要添加+=
的值取决于条件的位置.
如果你想真正比较if/else vs ternary,这将是一个更公平的比较(现在两者同样"慢",或者我们甚至可以说三元更快一点):
int diff;
if (i > 0)
diff = 2;
else
diff = 3;
value += diff;
Run Code Online (Sandbox Code Playgroud)
与
value += i > 0 ? 2 : 3;
Run Code Online (Sandbox Code Playgroud)
现在,对它的反汇编if/else
变为如下所示.请注意,这比三元情况稍差,因为它也使用循环变量(i
)的寄存器退出.
if (i > 0)
0000009d cmp dword ptr [ebp-20h],0
000000a1 jle 000000AD
{
diff = 2;
000000a3 mov dword ptr [ebp-24h],2
000000aa nop
000000ab jmp 000000B4
}
else
{
diff = 3;
000000ad mov dword ptr [ebp-24h],3
}
value += diff;
000000b4 mov eax,dword ptr [ebp-18h]
000000b7 mov edx,dword ptr [ebp-14h]
000000ba mov ecx,dword ptr [ebp-24h]
000000bd mov ebx,ecx
000000bf sar ebx,1Fh
000000c2 add eax,ecx
000000c4 adc edx,ebx
000000c6 mov dword ptr [ebp-18h],eax
000000c9 mov dword ptr [ebp-14h],edx
000000cc inc dword ptr [ebp-28h]
Run Code Online (Sandbox Code Playgroud)
编辑:
添加了一个可以使用if-else语句但不能使用条件运算符的示例.
在回答之前,请看一下[ 哪个更快?]在Lippert先生的博客上.我认为Ersönmez先生的回答是最正确的.
我想提一下我们应该用高级编程语言记住的东西.
首先,我从未听说条件运算符应该更快或者在C♯中使用if-else语句具有相同的性能.
原因很简单,如果if-else语句没有操作怎么办:
if (i > 0)
{
value += 2;
}
else
{
}
Run Code Online (Sandbox Code Playgroud)
条件运算符的要求是任何一方都必须有一个值,而在C♯中它也要求两边:
都有相同的类型.这只是使它与if-else语句不同.因此,您的问题成为一个问题,询问如何生成机器代码的指令,以便性能的差异.
使用条件运算符,在语义上它是:
无论评估表达式是什么,都有一个价值.
但是使用if-else语句:
如果表达式被评估为true,那么就做一些事情; 如果没有,做另一件事.
if-else语句不一定涉及值.您的假设只能通过优化来实现.
另一个展示它们之间差异的例子如下:
var array1=new[] { 1, 2, 3 };
var array2=new[] { 5, 6, 7 };
if(i>0)
array1[1]=4;
else
array2[2]=4;
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码编译,用条件运算符替换if-else语句就不会编译:
var array1=new[] { 1, 2, 3 };
var array2=new[] { 5, 6, 7 };
(i>0?array1[1]:array2[2])=4; // incorrect usage
Run Code Online (Sandbox Code Playgroud)
当你做同样的事情时,条件运算符和if-else语句在概念上是相同的,使用C中的条件运算符可能更快,因为C更接近平台的程序集.
对于您提供的原始代码,条件运算符用于foreach循环,这会使事情变得混乱以查看它们之间的差异.所以我建议使用以下代码:
public static class TestClass {
public static void TestConditionalOperator(int i) {
long value=0;
value+=i>0?2:3;
}
public static void TestIfElse(int i) {
long value=0;
if(i>0) {
value+=2;
}
else {
value+=3;
}
}
public static void TestMethod() {
TestConditionalOperator(0);
TestIfElse(0);
}
}
Run Code Online (Sandbox Code Playgroud)
以下是优化而不是IL的两个版本.由于它们很长,我使用的是图像显示,右侧是优化的:
在这两个版本的代码中,条件运算符的IL看起来比if-else语句短,并且仍然存在最终生成的机器代码的疑问.以下是两种方法的说明,前一种图像是非优化的,后一种是优化的:
在后者中,黄色块是仅在执行的代码i<=0
,并且蓝色块是在何时执行i>0
.在任一版本的指令中,if-else语句都较短.
请注意,对于不同的指令,[ CPI ]不一定相同.从逻辑上讲,对于相同的指令,更多的指令需要更长的周期.但是如果还考虑了指令获取时间和管道/缓存,那么实际的执行总时间取决于处理器.处理器还可以预测分支.
现代处理器拥有更多核心,事情可能更复杂.如果您是英特尔处理器用户,您可能需要查看[ 英特尔®64和IA-32架构优化参考手册 ].
我不知道是否有硬件实现的CLR,但如果是的话,你可能用条件运算符更快,因为IL明显更少.
注意:所有机器代码均为x86.
我做了Jon Skeet所做的事情,经历了1次迭代和1000次迭代,得到了OP和Jon的不同结果.在我的三元组中,三元组的速度稍快一些.以下是确切的代码:
static void runIfElse(int[] array, int iterations)
{
long value = 0;
Stopwatch ifElse = new Stopwatch();
ifElse.Start();
for (int c = 0; c < iterations; c++)
{
foreach (int i in array)
{
if (i > 0)
{
value += 2;
}
else
{
value += 3;
}
}
}
ifElse.Stop();
Console.WriteLine(String.Format("Elapsed time for If-Else: {0}", ifElse.Elapsed));
}
static void runTernary(int[] array, int iterations)
{
long value = 0;
Stopwatch ternary = new Stopwatch();
ternary.Start();
for (int c = 0; c < iterations; c++)
{
foreach (int i in array)
{
value += i > 0 ? 2 : 3;
}
}
ternary.Stop();
Console.WriteLine(String.Format("Elapsed time for Ternary: {0}", ternary.Elapsed));
}
static void Main(string[] args)
{
Random r = new Random();
int[] array = new int[20000000];
for (int i = 0; i < array.Length; i++)
{
array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);
long value = 0;
runIfElse(array, 1);
runTernary(array, 1);
runIfElse(array, 1000);
runTernary(array, 1000);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
我的程序的输出:
If-Else的经过时间:00:00:00.0140543
三元的经过时间:00:00:00.0136723
If-Else的经过时间:00:00:14.0167870
三元的经过时间:00:00:13.9418520
另一个以毫秒为单位的运行:
If-Else的经过时间:20
三元经过的时间:19
If-Else的经过时间:13854
三元的经过时间:13610
这是在64位XP中运行,我没有调试运行.
编辑 - 在x86中运行:
使用x86有很大的不同.这是在没有调试的情况下完成的,并且在与之前相同的xp 64位机器上,但是为x86 CPU构建.这看起来更像OP.
If-Else的经过时间:18
三元经过的时间:35
If-Else的经过时间:20512
三元经过的时间:32673
小智 5
生成的汇编代码将讲述故事:
a = (b > c) ? 1 : 0;
Run Code Online (Sandbox Code Playgroud)
产生:
mov edx, DWORD PTR a[rip]
mov eax, DWORD PTR b[rip]
cmp edx, eax
setg al
Run Code Online (Sandbox Code Playgroud)
鉴于:
if (a > b) printf("a");
else printf("b");
Run Code Online (Sandbox Code Playgroud)
产生:
mov edx, DWORD PTR a[rip]
mov eax, DWORD PTR b[rip]
cmp edx, eax
jle .L4
;printf a
jmp .L5
.L4:
;printf b
.L5:
Run Code Online (Sandbox Code Playgroud)
因此,如果您正在寻找真/假,那么三元组可以更短更快,因为使用的指令更少而且没有跳跃.如果使用1和0以外的值,您将获得与if/else相同的代码,例如:
a = (b > c) ? 2 : 3;
Run Code Online (Sandbox Code Playgroud)
产生:
mov edx, DWORD PTR b[rip]
mov eax, DWORD PTR c[rip]
cmp edx, eax
jle .L6
mov eax, 2
jmp .L7
.L6:
mov eax, 3
.L7:
Run Code Online (Sandbox Code Playgroud)
哪个与if/else相同.
归档时间: |
|
查看次数: |
36265 次 |
最近记录: |