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

前端 未结 12 2040
悲哀的现实
悲哀的现实 2021-02-01 02:56

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:20

    I'm sure you're confident this is a real time-taker.

    I would suppose asking the machine would give a more reliable answer than any of us could give.

    I've found, even in code like you're talking about, my supposition that I knew where the time was going was not quite correct. For example, if this is in an inner loop, if there is any sort of function call, even an invisible one inserted by the compiler, the cost of that call will dominate by far.

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

    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:22

    It depends on the architecture, but the x == -1 is more error-prone. x < 0 is the way to go.

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

    Same, both operations are usually done in 1 clock.

    0 讨论(0)
提交回复
热议问题