How to write the clear() method in the list data structure?

BlackCat :

I have read some frameworks source code recently and noticed that they written the clear() method of a list-like data structure like this. Delete the elements one by one.

while (_arr.length > 0 )
{

    remove(_arr[0]);

}       

(maybe the above look like a little confusing,but it's because the native array type in this language itself was a dynamic array) or

 for (int i = 0; i < size; i++)
  { elementData[i] = null;}
 size = 0;

But i remembered i have written some code like this. The list decorated native array type,and I have written clear() method like this.

 _arr=new Array();
 _size=0;

instantiate a new native array type directly.

and this code are written in the language that has the garbage collection. so I think all elements finally will be collected,so why there need a loop?Is a new will be fast?

Eran :

I guess the motivation is re-using the existing backing array instead of allocating a new one. This is important especially when the backing array is very large (which in some rare cases can even mean the new array cannot be allocated before the old one is garbage collected).

Allocating a new array (and garbage collecting the old one) is probably more time consuming than iterating over the existing array and setting the references of all the elements to null.

EDIT: As mentioned in the comments, setting the references to null in an array based List is not enough. You also have to indicate that the List is empty. In java.util.ArrayList this is done by setting the size property to 0.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422206&siteId=1