代码如下:
#include <iostream>
using std::cout;
int _tmain(int argc, _TCHAR* argv[])
{
const int SIZE = 1000;
int ia[SIZE];
for (size_t i = 0; i < SIZE; i++) {
ia[i] = i;
}
int ib[SIZE];
int *ip = ib;
for (size_t i = 0; i < SIZE; i++) {
*ip++ = i;
}
for (size_t i = 0; i < SIZE; i++)
{
cout << ia[i] << " " << ib[i] << "\n";
}
return 0;
}
vs2013编译后的汇编代码:
.text:00415E0F mov eax, [ebp+iter]
.text:00415E15 add eax, 1
.text:00415E18 mov [ebp+iter], eax // 给i加1
.text:00415E1E
.text:00415E1E loc_415E1E: ; CODE XREF: _wmain+3Dj
.text:00415E1E cmp [ebp+iter], 1000
.text:00415E28 jnb short loc_415E3F
.text:00415E2A mov eax, [ebp+iter] // 取下标
.text:00415E30 mov ecx, [ebp+iter] // 取值
.text:00415E36 mov [ebp+eax*4+ia], ecx // 将值赋给数组下标
.text:00415E3D jmp short loc_415E0F
.text:00415E3F ; ---------------------------------------------------------------------------
.text:00415E3F
.text:00415E3F loc_415E3F: ; CODE XREF: _wmain+58j
.text:00415E3F lea eax, [ebp+_Val]
.text:00415E45 mov [ebp+ib], eax
.text:00415E4B mov [ebp+iter1], 0
.text:00415E55 jmp short loc_415E66
.text:00415E57 ; ---------------------------------------------------------------------------
.text:00415E57
.text:00415E57 loc_415E57: ; CODE XREF: _wmain+BFj
.text:00415E57 mov eax, [ebp+iter1]
.text:00415E5D add eax, 1
.text:00415E60 mov [ebp+iter1], eax // 给i加1
.text:00415E66
.text:00415E66 loc_415E66: ; CODE XREF: _wmain+85j
.text:00415E66 cmp [ebp+iter1], 1000
.text:00415E70 jnb short loc_415E91
.text:00415E72 mov eax, [ebp+ib] // 获取地址
.text:00415E78 mov ecx, [ebp+iter1] // 获取值
.text:00415E7E mov [eax], ecx // 将值赋值给合适指针地址
.text:00415E80 mov edx, [ebp+ib]
.text:00415E86 add edx, 4
.text:00415E89 mov [ebp+ib], edx // 更新地址 + 4
.text:00415E8F jmp short loc_415E57
数组下标法使用了复杂指令,而指针法使用简单指令,具体执行时间看CPU对指令的执行时长,在执行较小的任务时,所产生的效率优势并不明显。