0

Which piece of code executes faster in Java?

List<Object> list = new ArrayList<Object>();
Object firstObject = null;
if (!list.isEmpty()) {
    firstObject = list.get(0);
}

or

List<Object> list = new ArrayList<Object>();
Object firstObject = null;
try {
    firstObject = list.get(0);
} catch (IndexOutOfBoundsException e) {
}
  • 1
    Try running a test. Execute the code lots of times and time it. – lurker Jun 05 '18 at 17:46
  • See https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Thiyagu Jun 05 '18 at 17:46
  • 1
    With pieces of code like you provided, it doesn't really matter, they will both be super fast. It would be better to use the empty list check however, rather than relying on an exception to handle empty list access. – Adam Jun 05 '18 at 18:16
  • Possible duplicate of [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – Zev Jun 06 '18 at 02:13
  • [Exception thrown](https://www.quora.com/How-expensive-is-the-try-catch-block-in-Java-in-terms-of-performance) tend to be relatively more expensive handle – deFreitas Jun 06 '18 at 03:03

1 Answers1

-1

I think the first approach would be better. Since we filtering the list before Getting the element from the list. The second statement list. get(0) will not execute.

Considering the second approach, It may throw exception.

Considering the run times, both execute at the same time.

Sanjay Anbu
  • 55
  • 1
  • 4
  • This is not a good answer. Either provide proof of your response or add a comment to better understand the question. – Adam Jun 05 '18 at 18:35