问题:
观察如下代码:
int a = 1;
int *p = &a;
auto p_ptr = p;//1
auto &p_ptr2 = p;//2
上述代码中1处和2处操作,哪个效率更高呢?
反汇编解读:
int a = 1;
00118178 mov dword ptr [a],1
int *p = &a;
0011817F lea eax,[a]
00118182 mov dword ptr [p],eax
auto p_ptr = p;//1
00118185 mov eax,dword ptr [p]
00118188 mov dword ptr [p_ptr],eax
auto &p_ptr2 = p;//2
0011818B lea eax,[p]
0011818E mov dword ptr [p_ptr2],eax
auto p_ptr = p;//1 此处在vs的反汇编中表示的是
(MOV在汇编语言中是 数据传送指令。)
00118185 mov eax,dword ptr [p] //将p放到寄存器当中
00118188 mov dword ptr [p_ptr],eax //将寄存器中的数据传送给p_ptr
-----------------------------------------------------------------------------------
auto &p_ptr2 = p;//2 此处在vs的反汇编中表示的是
(LEA 其取变量的地址)
0011818B lea eax,[p] //取变量p的地址,存放在寄存器中
0011818E mov dword ptr [p_ptr2],eax //将寄存器中的数据传送给p_ptr
dword 双字 就是四个字节
ptr pointer缩写 即指针
文章中写道:
( LEA AX,[1000H],作用是将内存单元[1000H]的偏移地址1000H送至AX;
MOV AX,[1000H],作用是将内存单元[1000H]的内容1234H送给AX)
What is the difference between MOV and LEA?stackoverflow.comLEA
加载有效地址MOV
表示负载值- lea只执行计算,它不加载任何东西,加载意味着触摸内存
有人会质疑是否和编译器优化有关系
经过验证发现,只要创建对象被使用过,其汇编release和debug是类似的。若申请了但是未使用,优化前后的代码会有区别。
如下为debug语句:
int a = 1;
00778178 mov dword ptr [a],1
int *p = &a;
0077817F lea eax,[a]
00778182 mov dword ptr [p],eax
auto p_ptr = p;//1
00778185 mov eax,dword ptr [p]
00778188 mov dword ptr [p_ptr],eax
auto &p_ptr2 = p;//2
0077818B lea eax,[p]
0077818E mov dword ptr [p_ptr2],eax
如下为release反汇编
int a = 1;
int *p = &a;
auto p_ptr = p;//1
auto &p_ptr2 = p;//2------>未使用
cout << &p<<p<<endl;
00E112B0 mov ecx,dword ptr ds:[0E13040h]
00E112B6 lea eax,[a]
00E112B9 push 0E11750h
00E112BE push eax
00E112BF mov dword ptr [p],eax
00E112C2 lea eax,[p]
00E112C5 push eax
00E112C6 mov dword ptr [a],1
00E112CD call dword ptr ds:[0E13024h]
00E112D3 mov ecx,eax
00E112D5 call dword ptr ds:[0E13024h]
00E112DB mov ecx,eax
00E112DD call dword ptr ds:[0E13048h]
使用了p_ptr2的反汇编:
int a = 1;
int *p = &a;
auto p_ptr = p;//1
auto &p_ptr2 = p;//2
cout << &p << p << p_ptr2 << &p_ptr2<<endl;
000B12B0 mov ecx,dword ptr ds:[0B3040h]
000B12B6 lea eax,[a]
000B12B9 mov dword ptr [p],eax ----->新增
000B12BC lea eax,[p]
000B12BF push 0B1760h
000B12C4 push eax
000B12C5 lea eax,[a]
000B12C8 mov dword ptr [a],1
000B12CF push eax
000B12D0 push eax
000B12D1 lea eax,[p]
000B12D4 push eax
000B12D5 call dword ptr ds:[0B3024h]
000B12DB mov ecx,eax
000B12DD call dword ptr ds:[0B3024h]
000B12E3 mov ecx,eax
000B12E5 call dword ptr ds:[0B3024h]
000B12EB mov ecx,eax
000B12ED call dword ptr ds:[0B3024h]
000B12F3 mov ecx,eax
000B12F5 call dword ptr ds:[0B3048h]
mov和lea