Search code examples
javareferencepass-by-referencehardcode

Java - Is it better to pass reference or work with hardcoded objects if possible


Is it worth to make better code (ClassB) instead of going with two separate check methods? So main question is: am I right when assuming that Class A is a bit faster than Class B, or is its difference doesn't really matter and passing variables (List in this situation) doesn't really affect productivity, even if these lists had 1000 objects each? Sorry if this question is dumb.

 public class ClassA implements Runnable {

    ArrayList<Obj> list1;
    ArrayList<Obj> list2;

    boolean checkList1() {
        for (Obj str : list1) {
            if (str.check()) {
                return true;
            }
        }
        return false;
    }

    boolean checkList2() {
        for (Obj str : list2) {
            if (str.check()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void run() {
        checkList1();
        checkList2();
    }
}

OR

 public class ClassB implements Runnable {

    ArrayList<Obj> list1;
    ArrayList<Obj> list2;

    boolean checkAnyList(ArrayList<Obj> list) {
        for (Obj str : list) {
            if (str.check()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void run() {
        checkAnyList(list1);
        checkAnyList(list2);
    }

}

Solution

  • In the end, you should just measure it. For that, you can use a high precision timer like System.nanoTime()

    Without measuring I would prefer classB. The following issues make classB more interesting

    • avoiding nearly duplicated code
    • more flexible when introducing more lists
    • JIT compiler improves code depending on the number of calls. So the method in classB reaches much earlier the threshold to improve.
    • it is not likely that a static available list is faster than a referenced one. The little advantage of classA not to pass a list, does only save a very little startup time.

    Just wait until I get real figures....