Why do associative arrays throw an Error (RangeError) on value not found?

bearophile bearophileHUGS at lycos.com
Tue Dec 31 06:00:21 PST 2013


John Colvin:

> Doesn't that duplicate the work of discovering whether the key 
> is there or not? I guess it would depend on the implementation.

If you compile the code with ldc2, the compiler in most cases is 
able to perform the associative array lookup only once. Elsewhere 
I suggested to add the same optimization to dmd.

With dmd currently you can avoid the double lookup manually 
because "key in aa" doesn't return a boolean as logic and good 
practice suggests, it returns a pointer that is null when the key 
is not found, and it points to the value when the key is present. 
So storing and dereferencing this pointer you can avoid the 
double lookup.

Bye,
bearophile


More information about the Digitalmars-d mailing list