associative arrays

Jonathan M Davis jmdavisProg at
Sat Jan 7 19:05:16 PST 2012

On Saturday, January 07, 2012 21:54:07 bearophile wrote:
> Maybe D associative arrays too should have both kinds of deleting methods
> :-)

Why? What's the gain? If you care that the element is already in the AA, then 
do either

assert(key in aa);


enforce(key in aa);

I suppose that that's less efficient than remove throwing on failure, since it 
has to do a double lookup, but since throwing the exception costs _far_ more 
than that, I don't think that the extra cost really matters

But if you _don't_ care whether the element is in the AA when you remove it, 
and remove threw when the element wasn't there, then you'd have to do

if(key in aa)

which would result is a double lookup when you don't want one, and performance 
_would_ matter, since there isn't necessarily another operation which would 
cost a lot which is overshadowing the cost of the double lookup (as occurs in 
the case where you throw the exception when the element isn't there). Also, if 
you considered the key not being there to be a bug (as seems more likely to 
me), the fact that remove then threw an assertion would force you to do the 
extra check _anyway_.

assert(key in aa);

So, as far as I can tell, the current situation is more efficient, and it 
doesn't cost you any expressiveness. You can still have an exception thrown 
when remove fails if you use enforce before the call if you want an exception 
thrown when the element isn't there.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list