正如 dwn 所说,在复杂处理器兴起期间,性能是其优势之一,MSDN 博客Non-classical processor behavior: How doing something can be faster than not doing it 举了一个例子,清楚地说明了三元(条件)运算符和 if/else 语句之间的区别。
给出以下代码:
#include <windows.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
int array[10000];
int countthem(int boundary)
{
int count = 0;
for (int i = 0; i < 10000; i++) {
if (array[i] < boundary) count++;
}
return count;
}
int __cdecl wmain(int, wchar_t **)
{
for (int i = 0; i < 10000; i++) array[i] = rand() % 10;
for (int boundary = 0; boundary <= 10; boundary++) {
LARGE_INTEGER liStart, liEnd;
QueryPerformanceCounter(&liStart);
int count = 0;
for (int iterations = 0; iterations < 100; iterations++) {
count += countthem(boundary);
}
QueryPerformanceCounter(&liEnd);
printf("count=%7d, time = %I64d\n",
count, liEnd.QuadPart - liStart.QuadPart);
}
return 0;
}
不同边界的成本有很大不同和奇怪(参见原始材料)。而如果改变:
if (array[i] < boundary) count++;
到
count += (array[i] < boundary) ? 1 : 0;
现在执行时间与边界值无关,因为:
优化器能够从三元表达式中删除分支。
但是在我的台式机 intel i5 cpu/windows 10/vs2015 上,我的测试结果与 msdn 博客完全不同。
使用调试模式时,if/else 开销:
count= 0, time = 6434
count= 100000, time = 7652
count= 200800, time = 10124
count= 300200, time = 12820
count= 403100, time = 15566
count= 497400, time = 16911
count= 602900, time = 15999
count= 700700, time = 12997
count= 797500, time = 11465
count= 902500, time = 7619
count=1000000, time = 6429
和三元运算符成本:
count= 0, time = 7045
count= 100000, time = 10194
count= 200800, time = 12080
count= 300200, time = 15007
count= 403100, time = 18519
count= 497400, time = 20957
count= 602900, time = 17851
count= 700700, time = 14593
count= 797500, time = 12390
count= 902500, time = 9283
count=1000000, time = 7020
使用释放模式时,if/else 成本:
count= 0, time = 7
count= 100000, time = 9
count= 200800, time = 9
count= 300200, time = 9
count= 403100, time = 9
count= 497400, time = 8
count= 602900, time = 7
count= 700700, time = 7
count= 797500, time = 10
count= 902500, time = 7
count=1000000, time = 7
和三元运算符成本:
count= 0, time = 16
count= 100000, time = 17
count= 200800, time = 18
count= 300200, time = 16
count= 403100, time = 22
count= 497400, time = 16
count= 602900, time = 16
count= 700700, time = 15
count= 797500, time = 15
count= 902500, time = 16
count=1000000, time = 16
三元运算符比我机器上的 if/else 语句慢!
所以根据不同的编译器优化技术,内部运算符和 if/else 的行为可能会有很大的不同。