Using "in" with associative arrays and then indexing them (efficiency)

Jonathan M Davis jmdavisProg at
Tue Jan 3 03:07:40 PST 2012

On Tuesday, January 03, 2012 11:52:13 Matej Nanut wrote:
> Hello everyone,
> I would like to know whether
>         if (symbol in symbols)
>                 return symbols[symbol];
> is any less efficient than
>         auto tmp = symbol in symbols;
>         if (tmp !is null)
>                 return *tmp;
> Without optimisation, it looks like the first example
> searches for `symbol' twice.

Of course it does. in does a search and returns a pointer to the element in 
the AA (or null if it isn't there). The subscript operator also does a search, 
returning the element if it's there and blowing up if it's not 
(OutOfRangeError IIRC without -release and who-knows-what with -release). So, 
if you use in and then the subscript operator, of course it's going to search 
twice. Part of the point of using in is to not have to do a double lookup 
(like you would be doing if AAs had a contains function and you called that 
prior to using the substript operator).

The correct way to do it is the second way, though you should be able to 
reduce it to

if(auto tmp = symbol in symbols)
    return *tmp;

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list