Do temp variables slow down my program?

前端 未结 5 858
悲&欢浪女
悲&欢浪女 2020-11-28 08:42

Suppose I have the following C code:

int i = 5;
int j = 10;
int result = i + j;

If I\'m looping over this many times, would it be faster to

5条回答
  •  感动是毒
    2020-11-28 09:02

    A modern optimizing compiler should optimize those variables away, for example if we use the following example in godbolt with gcc using the -std=c99 -O3 flags (see it live):

    #include 
    
    void func()
    {
      int i = 5;
      int j = 10;
      int result = i + j;
    
      printf( "%d\n", result ) ;
    }
    

    it will result in the following assembly:

    movl    $15, %esi
    

    for the calculation of i + j, this is form of constant propagation.

    Note, I added the printf so that we have a side effect, otherwise func would have been optimized away to:

    func:
      rep ret
    

    These optimizations are allowed under the as-if rule, which only requires the compiler to emulate the observable behavior of a program. This is covered in the draft C99 standard section 5.1.2.3 Program execution which says:

    In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

    Also see: Optimizing C++ Code : Constant-Folding

提交回复
热议问题