user1899020 user1899020 - 2 months ago 9
C++ Question

performance comparison when arguments are pre-known?

I have a function

enum Limit {MIN, MAX};

inline int f(pair<int, int> p, Limit l)
{
return l == MIN ? p.first : p.second;
}


Compare the computatinal time of
f(p, MIN)
and
p.first
, is the first one slower even with a good compiler in release version?

Answer

Questions of performance are impossible to answer through prediction. It entirely depends on what optimisations the compiler is able to make.

In this contrived case:

#include <utility>

enum Limit {MIN, MAX};

inline int f(std::pair<int, int> p, Limit l)
{
    return l == MIN ? p.first : p.second;
}

extern void emit(int);
int main()
{
  auto p = std::make_pair(4, 5);
  emit(f(p, MIN));
  emit(p.first);
}

There is no difference whatsoever:

main:                                   # @main
        pushq   %rax

        movl    $4, %edi
        callq   emit(int)

        movl    $4, %edi
        callq   emit(int)

        xorl    %eax, %eax
        popq    %rcx
        retq
Comments