.. will the compiler optimize calling of methodY two times or it will just let it be?
There is no rule for that. It depends on the compiler.
For instance, if methodY
always return true, the compiler is allowed to optimize your code by inlining methodY
like:
int methodX() {
..some operations.. (from methodY)
..some operations.. (from methodY)
return true;
}
But whether it will do it, we can't tell by just looking at the C++ source.
With gcc you can use the option -S
to generate an assembly source file (.s file). Looking into that file is the way to tell what the compiler did.
There are also some online site like https://godbolt.org/ that you can use. Here is an example:
#include <stdio.h>
int methodY()
{
printf("y\n");
return 1;
}
int methodX() {
if(methodY() == 1)
return methodY();
return 0;
}
int main(){
if (methodX()) printf("m\n");
return 0;
}
compiled with -O3
it shows:
.LC0:
.string "y"
methodY():
sub rsp, 8
mov edi, OFFSET FLAT:.LC0
call puts
mov eax, 1
add rsp, 8
ret
methodX():
sub rsp, 8
mov edi, OFFSET FLAT:.LC0
call puts
mov edi, OFFSET FLAT:.LC0
call puts
mov eax, 1
add rsp, 8
ret
.LC1:
.string "m"
main:
sub rsp, 8
mov edi, OFFSET FLAT:.LC0
call puts
mov edi, OFFSET FLAT:.LC0
call puts
mov edi, OFFSET FLAT:.LC1
call puts
xor eax, eax
add rsp, 8
ret
As you can see main
never calls methodX
but simply do the three prints directly. So in this case the functions were optimized away.