堆叠if语句的优化可能性?

时间:2014-07-23 21:34:42

标签: java optimization

private String formatPrice(int price) {
    String p = "";
    if (price > 10000000) {
        p = " (" + ((double) Math.round(price / 100000) / 10) + "m)";
    } else if (price > 100000) {
        p = " (" + (price / 1000) + "k)";
    } else if (price > 1000) {
        p = " (" + ((double) Math.round(price / 100) / 10) + "k)";
    } else if (price > 0) {
        p = " (" + price + "gp)";
    }
    return p;
}

是否可以在不降低性能的情况下简化这段代码?它看起来并没有正确完成。

2 个答案:

答案 0 :(得分:1)

  

是否可以在不降低性能的情况下简化这段代码?

如果我理解你的问题,是的!你可以使方法静态。您还可以使用String.format()

显着缩短它
private static String formatPrice(int price) {
  if (price < 0) {
    return "";
  }
  if (price > 1000 * 1000) {
    return String.format("(%.1fm)", ((double) price) / (1000 * 1000));
  } else if (price > 1000) {
    return String.format("(%dk)", price / 1000);
  }
  return String.format("(%dgp)", price);
}

答案 1 :(得分:0)

对我来说没问题。我没有看到任何可以在这里完成的大优化。它也很干净。但是,您可能希望看到相同算法的alternative implementations