I am trying to research what is the most efficient way to do value assignment in C/C++. And have some funny findings.
Suppose I want to assign value to a variable.
Firstly, I directly assign the constant value to the variable.
auto start = high_resolution_clock::now();
for (int index = 0; index < 100000; ++index)
{
a = 1;
}
auto stop = high_resolution_clock::now();
The corresponding assembly code is
Run in Visual Studio 2019 of my laptop, it takes about 190 microseconds.
Then I change the code to
int c = 1;
auto start = high_resolution_clock::now();
for (int index = 0; index < 100000; ++index)
{
a = c;
}
The running time jumps to 240 microseconds, which is as expected because there is extra time to get value of c, see as below assembly code.
Now, I change the code to read value from a static array.
int b[] = { 1,2 };
auto start = high_resolution_clock::now();
for (int index = 0; index < 100000; ++index)
{
a = b[0];
}
There are two more instructions to find address of array item.
But the funny thing is: the execution time drops to 230 microseconds, a little lower than the second case.
Can anybody help explain why the time of the third case is less than the second case?
Note: I run each case several times, and the time is average of several runs.