Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any big difference between using contains or loop through a list?

Performance wise, is there really a big difference between using:

  • ArrayList.contains(o) vs foreach|iterator
  • LinkedList.contains(o) vs foreach|iterator

Of course, for the foreach|iterator loops, I'll have to explicitly compare the methods and return true or false accordingly.

The object I'm comparing is an object where equals() and hashcode() are both properly overridden.

EDIT: Don't need to know about containsValue after all, sorry about that. And yes, I'm stupid... I realized how stupid my question was about containsKey vs foreach, nevermind about that, I don't know what I was thinking. I basically want to know about the ones above (edited out the others).

like image 495
rfgamaral Avatar asked May 21 '10 21:05

rfgamaral


People also ask

Is contain faster than a loop?

Contains() is about the same speed as, or slightly faster than, the loop. Here's my test code. To test this code, you should compile it as an x86 RELEASE build, and run it from outside the debugger. As you can see, the loop takes around 1/3 the time on my system.

What is faster than for loop in Java?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

What is the complexity of Contains method in Java?

contains() method requires O(n) time. So the time we spend to find a specific object here depends on the number of items we have in the array.

Which is better out of normal for loop or forEach loop?

The for loop is harder to read and write than the foreach loop. The foreach loop is easier to read and write than the for loop. The for loop is used as a general purpose loop. The foreach loop is used for arrays and collections.


1 Answers

EDITED:

With the new form of the question no longer including HashMap and TreeMap, my answer is entirely different. I now say no.

I'm sure that other people have answered this, but in both LinkedList and ArrayList, contains() just calls indexOf(), which iterates over the collection.

It's possible that there are tiny performance differences, both between LinkedList and ArrayList, and between contains and foreach, there aren't any big differences.

like image 135
CPerkins Avatar answered Sep 21 '22 14:09

CPerkins