查看在这个级别发生了什么样的优化的唯一方法是编译和反汇编。事实证明,编译器已经非常擅长删除或重新解释您的代码以使其更快。
我使用 MS C 编译器编译了这段代码:
int main()
{
int a = 1;
int b = 2;
int c;
// Force use of the variables so they aren't optimized away
printf("a = %d, b = %d\n", a, b);
c = b;
b = a;
a = c;
// Force use again
printf("a = %d, b = %d\n", a, b);
return 0;
}
这是优化后的实际输出,为简洁而编辑:
; 4 : int a = 1;
; 5 : int b = 2;
; 6 : int c;
; OPTIMISED AWAY
; 8 : printf("a = %d, b = %d\n", a, b);
push 2
push 1
push pointer_to_string_constant
call DWORD PTR __imp__printf
; 10 : c = b;
; 11 : b = a;
; 12 : a = c;
; OPTIMISED AWAY
; 14 : printf("a = %d, b = %d\n", a, b);
push 1
push 2
push pointer_to_string_constant
call DWORD PTR __imp__printf
; 16 : return 0;
xor eax, eax ; Just a faster way of saying "eax = 0;"
; 17 : }
ret 0
所以你看,编译器决定在这种情况下根本不使用任何变量,而只是将整数直接压入堆栈(这与将参数传递给 C 中的函数相同)。
这个故事的寓意是不要在涉及微优化时对编译器进行第二次猜测。