views:

103

answers:

2

Compare

    synchronized (countList) {
        while (iter.hasNext()) {
            Entry<Long, Long> entry = iter.next();
            if(entry.getVaue>0)
                 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.

A: 

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();
    }
}
adrian.tarau
Why comment that clear() is better, and then provide an example which uses remove()?
Software Monkey
See polygenelubricants's response
adrian.tarau
+11  A: 

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
polygenelubricants
clear is definitely better
KitsuneYMG
You should've said "clear is clearly better" =)
polygenelubricants
Pretty much by definition clear will *always* be at least as good, and with *very* few exceptions, orders of magnitude better.
Software Monkey