Are compilers smart enough to detect a no-op function?

If I write a function like this:

void doMaybeNothing()
{ 
#ifndef IM_LAZY
   doSomething();
#endif
}

Are modern compilers smart enough to detect no-op functions and optimize, so there are no cycles in vain? Or is there a slight impact on performance?

+3
source share
4 answers

Assuming that the function body is available at compile time or in binding time (i.e. not in a dynamically linked library), most modern compilers should get rid of function calls that do nothing (if optimization is enabled, of course).

, , , . , , .

+6

, , .

gcc

#include <stdio.h>

void no_op () {}

int main () {
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    no_op();
    return 0;
}

( -O1)

    .section __TEXT,__text,regular
    .section __TEXT,__textcoal_nt,coalesced
    .section __TEXT,__const_coal,coalesced
    .section __TEXT,__picsymbolstub4,symbol_stubs,none,16
    .text
    .align 2
    .globl _no_op
_no_op:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 0, uses_anonymous_args = 0
    @ link register save eliminated.
    @ lr needed for prologue
    bx  lr
    .align 2
    .globl _main
_main:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 0, uses_anonymous_args = 0
    @ link register save eliminated.
    @ lr needed for prologue
    mov r0, #0
    bx  lr
    .subsections_via_symbols

, no_op main .

+4

doMaybeNothing , .

, , , .

: . , .

+1

, , , , , #ifndef , , .
, , . , , IM_LAZY , :

void MaybeDoNothing()
{
}

void MaybeDoNothing()
{
    doSomething();
}
0

Source: https://habr.com/ru/post/1748758/


All Articles