Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On a java TreeMap should i check size before clearing?

Tags:

java

I've assumed that i can just call clear instead of

if (tmap.size() > 0) {
    tmap.clear();
}

Or is one more efficient?

like image 602
simgineer Avatar asked Feb 10 '26 13:02

simgineer


1 Answers

You will gain nothing because TreeMap.clear() is nothing in terms of overhead :

public void clear() {
    modCount++;
    size = 0;
    root = null;
}

So keep your code simple to read with just tmap.clear();

JDK collections classes are written to be optimized as much as possible.
So you generally don't need to worry about basic optimizations because these are bound to be done.
For example look at the HashMap.clear() logical, the clear() operation requires a little more overhead : clearing the table (buckets).
As a consequence, the size of the map is checked before performing that :

public void clear() {
    Node<K,V>[] tab;
    modCount++;
    if ((tab = table) != null && size > 0) {
        size = 0;
        for (int i = 0; i < tab.length; ++i)
            tab[i] = null;
    }
}
like image 165
davidxxx Avatar answered Feb 13 '26 10:02

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!