What is faster (x < 0) or (x == -1)?

前端 未结 12 2050
栀梦
栀梦 2021-02-01 03:00

Variable x is int with possible values: -1, 0, 1, 2, 3. Which expression will be faster (in CPU ticks):

1. (x < 0)
2. (x == -1)


        
相关标签:
12条回答
  • 2021-02-01 03:17

    Nikolay, you write:

    It's actually bottleneck operator in the high-load program. Performance in this 1-2 strings is much more valuable than readability...

    All bottlenecks are usually this small, even in perfect design with perfect algorithms (though there is no such). I do high-load DNA processing and know my field and my algorithms quite well

    If so, why not to do next:

    1. get timer, set it to 0;
    2. compile your high-load program with (x < 0);
    3. start your program and timer;
    4. on program end look at the timer and remember result1.
    5. same as 1;
    6. compile your high-load program with (x == -1);
    7. same as 3;
    8. on program end look at the timer and remember result2.
    9. compare result1 and result2.

    You'll get the Answer.

    0 讨论(0)
  • 2021-02-01 03:20

    Both operations can be done in a single CPU step, so they should be the same performance wise.

    0 讨论(0)
  • 2021-02-01 03:24

    x < 0 will be faster. If nothing else, it prevents fetching the constant -1 as an operand. Most architectures have special instructions for comparing against zero, so that will help too.

    0 讨论(0)
  • 2021-02-01 03:25

    Try it and see! Do a million, or better, a billion of each and time them. I bet there is no statistical significance in your results, but who knows -- maybe on your platform and compiler, you might find a result.

    This is a great experiment to convince yourself that premature optimization is probably not worth your time--and may well be "the root of all evil--at least in programming".

    0 讨论(0)
  • 2021-02-01 03:25

    It could be dependent on what operations precede or succeed the comparison. For example, if you assign a value to x just before doing the comparison, then it might be faster to check the sign flag than to compare to a specific value. Or the CPU's branch-prediction performance could be affected by which comparison you choose.

    But, as others have said, this is dependent upon CPU architecture, memory architecture, compiler, and a lot of other things, so there is no general answer.

    0 讨论(0)
  • 2021-02-01 03:26

    You can't even answer this question out of context. If you try for a trivial microbenchmark, it's entirely possible that the optimizer will waft your code into the ether:

    // Get time
    int x = -1;
    for (int i = 0; i < ONE_JILLION; i++) {
        int dummy = (x < 0); // Poof!  Dummy is ignored.
    }
    // Compute time difference - in the presence of good optimization
    // expect this time difference to be close to useless.
    
    0 讨论(0)
提交回复
热议问题