【问题标题】:looping with if condition versus ternary operator which is more faster any why [duplicate]使用 if 条件与三元运算符循环,后者更快,为什么 [重复]
【发布时间】:2020-05-30 19:19:26
【问题描述】:

以下哪个更有效,为什么

  1. 循环遍历列表并检查最大值并求和为整数
    public List<Integer> returnComparision(List<Integer> a, List<Integer> b){

        List<Integer> resultLoop = null;
        int aResult = 0;
        int bResult=0;
        for(int i=0; i <a.size() ; i++){
            if(a.get(0) > b.get(0)){
                aResult += 1;
            }
            else {
                bResult += 1;
            }

        }
        resultLoop.add(aResult);
        resultLoop.add(bResult);

        return resultLoop;
    }

或使用三进制将总数推入List

public List<Integer> returnComparision(List<Integer> a, List<Integer> b){

        List<Integer> result = null;

        result.add( ((a.get(0) > b.get(0)?1:0)  + ((a.get(1) > b.get(1))?1:0)) + ((a.get(2) > b.get(2))?1:0) );
        result.add( ((b.get(0) > a.get(0)?1:0)  + ((b.get(1) > a.get(1))?1:0)) + ((b.get(2) > a.get(2))?1:0) );

        return result;
    }

【问题讨论】:

  • 获取分析器并尝试一下!我的猜测:速度上没有显着差异,但在可读性上。或者,当编译器优化循环体时,循环的第一个代码可能更快。
  • 它们都会非常快速地生成空指针异常。

标签: java


【解决方案1】:

两者都不是更快。它们将编译为相同的字节码——三元运算与if/else 语句相同。它只是语法糖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 2015-06-05
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2021-03-31
    • 2012-09-20
    • 2017-08-26
    相关资源
    最近更新 更多