0

I have code like this:

public int getDistanceToNumber(int number) {
    List<Integer> tuple5 = null;
    int distanceCounter = 0;
    for (int i = 0; i < allDraws.size(); i++) {
        tuple5 = allDraws.get(i).getTupleAsList();
        if (tuple5.contains(number)) {  // autoboxing primitive ?

        }

    }

    return 0;
}

The question is - shall I make method argument Integer like int getDistanceToNumber(Integer number) for autoboxing from primitive into Integer to happen only once, or there is no performance issue.

This piece of code inside loop runs over 100K times...

caasdads
  • 409
  • 4
  • 12
  • Did you look at the generated bytecode and/or perform benchmarks? – UnholySheep Nov 11 '18 at 19:35
  • Have you benchmarked this with JMH and determined that it's in need of optimization? – Jacob G. Nov 11 '18 at 19:35
  • 2
    Don't change the method signature. Instead, you can create a local variable with the boxed `int` value. As for performance, the sequential search of the `List` is more of a problem. However, as others have suggested, don't micro-optimize the code without first analyzing the code by profiling it. – Andreas Nov 11 '18 at 19:36

1 Answers1

0

You should test that under a JMH.

  • You can avoid the boxing problem by using a Integer.valueOf(int) once and passing it to List::contains(Object).
  • The compiler may be efficient enough to understand that number is never changed and do that for you.

For the rest, without more information (type of allDraws ?), there might be other optimization to do before boxing conversion.

NoDataFound
  • 11,381
  • 33
  • 59