Ternar operator



  • What's the works faster?

    template <typename T> T abs(T n) {return n<0 ? -n : n;}
    

    or

    template <typename T> T abs(T n) {return n*(n<0 ? -1 : 1);}
    


  • Before I answer, I'll tell you what. this information will help nothing.♪ Why?

    • It's a template. It will be installed for each type separately, so the result depends heavily on type (code may not be computed with some types at all). You want to compare, tell me what type you're interested in. And I'll behave like C, and I'll assume. int
    • abs There's a standard library, and there's reason to think it's as effective as possible.
    • It's a micro-optimization that you don't think you'll notice at all times. Let's just say, the time you're saving is likely to cost all the users in the entire life of your program even the time I wrote this answer. :)

    But let's https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22C4TwDgpgJhBmAEBLAdseAVA3AKHfAhgEYDOAFHsgJTwDeAThMAK53LzIA8ADPAPzwBaNgC52mAL7ZcBEgCZy7avUYs2yAFSlOPfgICM8UXsoSgAA%22%2C%22compiler%22%3A%22g530%22%2C%22options%22%3A%22-O3%22%7D%5D%7D c int:

    typedef int T;
    T abs(T n) {return n<0 ? -n : n;}
    

    T abs2(T n) {return n*(n<0 ? -1 : 1);}

    Output at x86 GCC 5.3.0 with flag -O3:

    abs(int):
    movl %edi, %edx
    movl %edi, %eax
    sarl $31, %edx
    xorl %edx, %eax
    subl %edx, %eax
    ret
    abs2(int):
    movl %edi, %eax
    sarl $31, %eax
    orl $1, %eax
    imull %edi, %eax
    ret

    The code is different. As you can see, the second option is shorter. Does that mean he's faster? Not a fact. The result depends on implementation in the processor, but multiplication is technically more difficult to read, so it takes a little longer.

    But that's all about it. int♪ You can check the other types you're interested in, just putting him in. typedef The same instrument. But there's always one answer to "speed" questions. Measure!




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2