Which is better for read and removing a whole collection in java, iter.remove() or collection.clear()?
Compare
synchronized (countList) {
while (iter.hasNext()) {
Entry<Long, Long> entry = iter.next();
if(entry.getVaue>0)
开发者_如何学C entry.output();
}
countList.clear();
}
with
synchronized (countList) {
while (iter.hasNext()) {
Entry<Long, Long> entry = iter.next();
if(entry.getVaue>0)
entry.output();
iter.remove();
}
}
Is there a real difference? I am guessing that maybe garbage collection is better for the collection.clear
method.
There are situations where N
remove()
s through the iterator would yield O(N log N)
, or even worse, O(N^2)
performance (e.g. on an ArrayList
). I can't think of any scenario where clear()
would perform as badly.
I would say that clear()
is probably better. It's done as one operation, so implementations can optimize it better since it's not an incremental modification to the collection that remove()
is (where invariants need to be maintained, etc).
Also, collection iterators must guard against IllegalStateException
and/or ConcurrentModificationException
. With N
remove()
s, that's N
checks, which can add up. Finally, as a reminder, not all iterators support remove()
.
Think of it this way:
- N
remove()
operations are done through a middleman (the iterator), and it puts the collection intoN
different states before it becomes empty - 1
clear()
is a direct operation on the collection, and it's only 1 state transition
I presume iter.remove is called for every entry, right? It is better(performance degradation when removing one by one - it depends on the collection implementation how much slower) to invoke clear at the end or just let the collection to be garbage collected.
synchronized (countList) {
while (iter.hasNext()) {
Entry<Long, Long> entry = iter.next();
if(entry.getVaue>0) {
entry.output();
}
iter.remove();
}
}
精彩评论