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

前端 未结 12 2049
栀梦
栀梦 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:38

    As others have said there probably isn't any difference. Comparisons are such fundamental operations in a CPU that chip designers want to make them as fast as possible.

    But there is something else you could consider. Analyze the frequencies of each value and have the comparisons in that order. This could save you quite a few cycles. Of course you still need to compile your code to asm to verify this.

提交回复
热议问题