0

which of the below if more efficient and why

  1. Looping through a list and checking the greatest and summing into a integer
    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;
    }

or using ternary to push the total into 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;
    }
  • 1
    Get a profiler and try it! My guess: no significant difference in speed, but in readability. Or maybe the first code with the loop is faster when the compiler optimizes the loop body away. – Robert Feb 15 '20 at 03:17
  • 3
    They'll both be extremely fast at generating a null pointer exception. – Gene Feb 15 '20 at 03:33
  • Would you consider [Java 8 streams adding values from two or more lists](https://stackoverflow.com/questions/28592529/java-8-streams-adding-values-from-two-or-more-lists) – Abra Feb 15 '20 at 05:18

1 Answers1

1

Neither is faster. They will compile to the same bytecode - a ternary operation is the same as an if/else statement. It is just syntactical sugar.

Lewis
  • 4,285
  • 1
  • 23
  • 36