小编Dom*_*icR的帖子

为什么带有两个常量的三元运算符比带有变量的三元运算符快?

在Java中,我有两个不同的语句,它们通过使用三元运算符来完成相同的结果,如下所示:

  1. num < 0 ? 0 : num;
  2. num * (num < 0 ? 0 : 1);

看起来第二个语句不必要地复杂并且比第一个语句花费的时间更长,但是当我使用以下代码记录每个花费的时间时,结果如下:

final long startTime = System.currentTimeMillis();

Random rand = new Random();
float[] results = new float[100000000];
for (int i = 0; i < 100000000; i++) {
    float num = (rand.nextFloat() * 2) - 1;
    results[i] = num < 0 ? 0 : num;
    //results[i] = num * (num < 0 ? 0 : 1);
}

final long endTime = System.currentTimeMillis();

System.out.println("Total Time: " …
Run Code Online (Sandbox Code Playgroud)

java optimization performance conditional-operator

11
推荐指数
1
解决办法
487
查看次数