Using "in" with associative arrays and then indexing them	(efficiency)
    Ali Çehreli 
    acehreli at yahoo.com
       
    Tue Jan  3 12:17:45 PST 2012
    
    
  
On 01/03/2012 02:52 AM, Matej Nanut wrote:
 > 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.
Although the symbol is looked up twice, the cost may be negligible. 
Being hash tables, AAs have constant time lookup. Algorithmically, 
looking up twice is the same as looking up once in hash tables.
When we assume that the looked-up object is going to be used in a 
non-trivial operation, then it doesn't matter.
Having said that, I would use the second version too :D perhaps shorter as
     if (tmp) {
         // use *tmp
     }
Ali
    
    
More information about the Digitalmars-d-learn
mailing list