Performance wise, is there really a big difference between using:
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).
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With