Is it worth checking LinkedHashSet.contains (...) before adding?
I am using LinkedHashSet to implement a record-ordered collection. If a duplicate item is added, it must come at the end, and the entry already in the set must be removed.
I am debating whether it is worth checking set.contains (entry) before I call set.remove (entry)? Essentially the check contains () every time you suggest any time / space for just blindly calling remove () every time?
Set<Integer> set = new LinkedHashSet<>();
// The below
set.remove(entry);
set.add(entry);
// Versus the below
if (set.contains(entry)) {
set.remove(entry);
}
set.add(entry);
source to share
I would recommend against calling both contain and delete. Both calls must search chains to find an element, and contains
it does so no faster than remove
. This way, you potentially double your required call time each time.
You can view the code for contains
and remove
yourself.
You will find that both options are possibly iterating through the hash chains at some point ( remove
in the HashMap removeNode
and contains
in the HashMap getNode
), which can be fortunate if your set is under heavy load.
Unless your set is under heavy load, then it's probably not worth it anyway, but not a big deal, since in sparse hash chains the expected search / delete is O (1) (i.e. will be just as fast , whether you have 5 items or 5000).
source to share