Instead of guessing, why not take a look?
Compiling the following code:
#include <utility>
#include <iostream>
struct Window
{
std::pair<int, int> pos;
std::pair<int, int> getPosition() const
{
return pos;
}
};
int main()
{
Window window{{42, 314}};
for (int i = 0; i < 10000; ++i)
std::cout << (i + window.getPosition().first) << std::endl;
}
With Clang 6.0.0, with level 3 optimization:
main: # @main
push r15
push r14
push rbx
mov r15d, 42
.LBB0_1: # =>This Inner Loop Header: Depth=1
mov edi, offset std::cout
mov esi, r15d
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
mov r14, rax
; Continua...
Note that the 42
value has been passed to the r15d
register, and whenever the loop prints the value of the first pair member, it is passed as the pro std::cout.operator<<(int)
argument through the esi
register, copying direct from r15d
.
Something similar is done by GCC 8.1, with the same flags:
main:
push r12
push rbp
mov ebp, 42
push rbx
jmp .L7
; Continua...
.L7:
mov esi, ebp
mov edi, OFFSET FLAT:std::cout
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
mov r12, rax
; Continua...
The value of the first pair member is stored in register ebp
, which is passed as parameter to std::cout.operator<<(int)
by esi
as well.
See the two results on Godbolt .
As Maniero said, there are several factors at play when compiler optimizes your code and so you should avoid guessing what will happen to your code. Isolate the problem and compile locally to see what the result is. Then compile the whole project and see what the result is compared to the isolated code. Lastly, and more importantly, run profiling, or a benchmark, of isolated, non-isolated code, then optimize it in code (if necessary!) And compare the results with new profiling (I'm not even considering the architecture where your program will be running, but it would be nice too). Only then will you be sure that your manual optimizations have been successful.
In most cases, premature optimization (i.e. trying to guess the behavior of your program's execution and optimizing on top of it) is harmful and can make the optimizations that the compiler can do even worse.
Always optimize thinking about the data that your program will process and little in the construction of the code, comparing profiles to prove the success of the optimizations.