A compiler with enabled optimization (via flags) will take more time for the generation, but the execution of generated binary will most likely have a better performance.
Hint: If you are as lazy as I am you can use a web tool (https://godbolt.org/) to take a look on the generated assembly code for a choosen compiler.
Examples
For the following examples I have choosen GCC 9.2 (x86-64) as compiler.
Useless stuff removal
| Source code | Without optimization | With optimization (-O) |
|---|---|---|
void function()
{
int i;
i = 42;
}
|
function():
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 42
nop
pop rbp
ret
|
function():
ret
|
Pre-calculation
| Source code | Without optimization | With optimization (-O) |
|---|---|---|
int function()
{
int i = 0;
i++;
return i;
}
|
function():
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 0
add DWORD PTR [rbp-4], 1
mov eax, DWORD PTR [rbp-4]
pop rbp
ret
|
function():
mov eax, 1
ret
|