ArrayList Remove() vs RemoveAll() performanmce
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   gopi_nath
Posted On:   Wednesday, October 15, 2003 02:51 AM

what is the performance difference in terms of using
looped remove() over removeAll()

Re: ArrayList Remove() vs RemoveAll() performanmce

Posted By:   Benoit_Quintin  
Posted On:   Wednesday, October 15, 2003 07:32 AM

looking at the source code :
 
public boolean removeAll(Collection c) {
boolean modified = false;
Iterator e = iterator();
while (e.hasNext()) {
if(c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}

We can see that removeAll() calls the collection's (ArrayList in your case) remove(). Now looking at the remove() in ArrayList :
public Object remove(int index) {
RangeCheck(index);

modCount++;
Object oldValue = elementData[index];

int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work

return oldValue;
}
The remove is pretty inefficient, and if you want to do a removeAll, it's even worse, because you endup copying your array (size-1) times!!

Looking at clear() :

 public void clear() {
modCount++;

// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;

size = 0;
}
clear() in much faster (and leanier) performance-wise than removeAll() !!
About | Sitemap | Contact