Most efficient way to find smallest of 3 numbers Java?

后端 未结 17 2232
故里飘歌
故里飘歌 2020-12-14 05:44

I have an algorithm written in Java that I would like to make more efficient. A part that I think could be made more efficient is finding the smallest of 3 numbers. Currentl

相关标签:
17条回答
  • 2020-12-14 06:11

    No, it's seriously not worth changing. The sort of improvements you're going to get when fiddling with micro-optimisations like this will not be worth it. Even the method call cost will be removed if the min function is called enough.

    If you have a problem with your algorithm, your best bet is to look into macro-optimisations ("big picture" stuff like algorithm selection or tuning) - you'll generally get much better performance improvements there.

    And your comment that removing Math.pow gave improvements may well be correct but that's because it's a relatively expensive operation. Math.min will not even be close to that in terms of cost.

    0 讨论(0)
  • 2020-12-14 06:14
    double smallest;
    if(a<b && a<c){
        smallest = a;
    }else if(b<c && b<a){
        smallest = b;
    }else{
        smallest = c;
    }
    

    can be improved to:

    double smallest;
    if(a<b && a<c){
    smallest = a;
    }else if(b<c){
        smallest = b;
    }else{
        smallest = c;
    }
    
    0 讨论(0)
  • 2020-12-14 06:15

    I would use min/max (and not worry otherwise) ... however, here is another "long hand" approach which may or may not be easier for some people to understand. (I would not expect it to be faster or slower than the code in the post.)

    int smallest;
    if (a < b) {
      if (a > c) {
        smallest = c;
      } else { // a <= c
        smallest = a;
      }
    } else { // a >= b
      if (b > c) {
        smallest = c;
      } else { // b <= c
        smallest = b;
      }
    }
    

    Just throwing it into the mix.

    Note that this is just the side-effecting variant of Abhishek's answer.

    0 讨论(0)
  • 2020-12-14 06:17

    Works with an arbitrary number of input values:

     public static double min(double... doubles) {
        double m = Double.MAX_VALUE;
        for (double d : doubles) {
            m = Math.min(m, d);
        }
        return m;
    }
    
    0 讨论(0)
  • 2020-12-14 06:19

    It all looks ok, your code will be fine, unless you're doing this in a tight loop. I also would consider

    double min;
    min = (a<b) ? a : b;
    min = (min<c) ? min : c;
    
    0 讨论(0)
  • 2020-12-14 06:22

    OP's efficient code has a bug:

    when a == b, and a (or b) < c, the code will pick c instead of a or b.

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