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

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

提交回复
热议问题