Why Methode LinkedList.contains() runs quickly than such implementation:
for (String s : list)
if (s.equals(element))
return true;
return false;
I don’t see great difference between this to implementations(i consider that search objects aren’t nulls), same iterator and equals operation
Let’s have a look at the source code (OpenJDK version) of
java.util.LinkedListAs you can see, this is a linear search, just like the for-each solution, so it’s NOT asymptotically faster. It’d be interesting to see how your numbers grow with longer lists, but it’s likely to be a constant factor slower.
The reason for that would be that this
indexOfworks on the internal structure, using direct field access to iterate, as opposed to the for-each which uses anIterator<E>, whose methods must also additionally check for things likeConcurrentModificationExceptionetc.Going back to the source, you will find that the
E next()method returned by theIterator<E>of aLinkedListis the following:This is considerably “busier” than the
e = e.next;inLinkedList.contains! Theiterator()of aLinkedListis actually aListIterator, which has richer features. They aren’t needed in your for-each loop, but unfortunately you have to pay for them anyway. Not to mention all those defensive checks forConcurrentModificationExceptionmust be performed, even if there isn’t going to be any modification to the list while you’re iterating it.Conclusion
So yes, iterating a
LinkedListas a client using a for-each (or more straightforwardly, using itsiterator()/listIterator()) is more expensive than what theLinkedListitself can do internally. This is to be expected, which is whycontainsis provided in the first place.Working internally gives
LinkedListtremendous advantage because:So what can you learn from this? Familiarize yourself with the API! See what functionalities are already provided; they’re likely to be faster than if you’ve had to duplicate them as a client.