0

Im using arraylist to compare the elements in my selenium webdriver script in which I have compare the elemets from two different pages.

So which one is more efficient ?

Using same arraylist or creating the new one?

  • 3
    Most of the times I would create a new Arraylist and let the garbage collector decompose the list items references in its own sweet time. – Mritunjay Sep 26 '17 at 07:05

1 Answers1

0

The source code for removeAll()(As defined in AbstractCollection):

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<?> it = iterator();
    while (it.hasNext()) {
        if (c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}

The source code for clear()(As defined in ArrayList):

public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

clear() is much faster since it doesn't have to deal with all those extra method calls, but I think that instantiate a new ArrayList is the most efficient, in particular in a very big ArrayList (no need to iterate over the collection).