java - 通过堆叠 if 语句进行优化的可能性?

标签 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;
}

是否可以简化这段代码而不过多降低性能?看起来做得不太好。

最佳答案

Is it possible to simplify this piece of code without slowing down performance too much?

如果我理解你的问题,是的!您可以将该方法设为静态。您还可以使用 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);
}

关于java - 通过堆叠 if 语句进行优化的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921450/

相关文章:

python - 如何通过一个简单的循环获得真正快速的 Python

optimization - 从动态网站中删除多余的 css 规则

java - 命名枚举类型

java - Maven Spring 启动 :run against compiled jar

java - git pull 后无法解决冲突

mysql大查询优化

android - Android 上使用 OpenGL ES 1.0 的简单粒子系统

python - 自定义均值实现比 pandas 默认均值慢。如何优化?

java - Java7中方法句柄的用途是什么?

java - CustomListView未填充在Android的Fragment中