AA.remove in foreach && AA = new vs cleaning

Steven Schveighoffer schveiguy at yahoo.com
Fri Oct 23 06:03:38 PDT 2009


On Thu, 22 Oct 2009 19:58:40 -0400, Saaa <empty at needmail.com> wrote:

> Steven Schveighoffer wrote:
>>> So, what is the fastest way to clean an AA?
>>
>> aa = null;
> :(
>>
>> However, if you have multiple copies of the AA, this does not clear out
>> the data.  It merely resets the AA reference.
>>
>> I'd not trust your code
> :)
>> because it's undefined behavior.  If you want to  remove all the  
>> elements
>> individually, copy the keys to an array, then  iterate over the array
>> removing each element.
> This is what the dsource example does, it loops over a copy of all the  
> keys
> :)
> foreach(K key; aa.keys)
>  aa.remove(key);

If this works, it means that aa.keys returns a copy of the keys from aa,  
not a lazy view of the keys.  This makes it less efficient, but makes the  
removal possible.

In dcollections, the map keys property returns an iterator over the keys  
of the object.  It is a live view, so there is no copy of the keys, so  
running code like this for a dcollections HashMap for instance, would  
result in undefined behavior.

However, dcollections provides a way to safely iterate over a map and  
remove individual elements:

foreach(ref dopurge, k, v; hashmap)
{
    if(shouldRemove(k, v))
        dupurge = true;
}

>
>>
>> Or use a real collection class, such as Tango's or dcollections' and use
>> the clear() method :)
>>
>> -Steve
> As nulling is all it takes I don't think it's that much faster :)

As I said, nulling only clears the reference.  You could do the same thing  
with a container class. Here is an example:

int[int] aa1;
aa1[0] = 0;

auto aa2 = aa1;

aa1 = null; // does not clear aa2, all the data is still there.

Now, replace line one with

auto aa1 = new HashMap!(int, int);

And the same rules apply.  Except aa1.clear() will clear out *the  
elements* of aa1 and aa2.  That's what I was talking about.

-Steve


More information about the Digitalmars-d-learn mailing list