开发者

Which is better for read and removing a whole collection in java, iter.remove() or collection.clear()?

开发者 https://www.devze.com 2022-12-21 03:04 出处:网络
Compare synchronized (countList) { while (iter.hasNext()) { Entry<Long, Long> entry = iter.next();

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 into N 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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号