www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Using "in" with associative arrays and then indexing them (efficiency)

reply Matej Nanut <matejnanut gmail.com> writes:
SGVsbG8gZXZlcnlvbmUsCgpJIHdvdWxkIGxpa2UgdG8ga25vdyB3aGV0aGVyCgrCoMKgwqDCoMKg
wqDCoCBpZiAoc3ltYm9sIGluIHN5bWJvbHMpCsKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDC
oCByZXR1cm4gc3ltYm9sc1tzeW1ib2xdOwoKaXMgYW55IGxlc3MgZWZmaWNpZW50IHRoYW4KCsKg
wqDCoMKgwqDCoMKgIGF1dG8gdG1wID0gc3ltYm9sIGluIHN5bWJvbHM7CsKgwqDCoMKgwqDCoMKg
IGlmICh0bXAgIWlzIG51bGwpCsKgwqDCoMKgwqDCoMKgIMKgwqDCoMKgwqDCoMKgIHJldHVybiAq
dG1wOwoKV2l0aG91dCBvcHRpbWlzYXRpb24sIGl0IGxvb2tzIGxpa2UgdGhlIGZpcnN0IGV4YW1w
bGUKc2VhcmNoZXMgZm9yIGBzeW1ib2wnIHR3aWNlLgoKVGhhbmtzLApNYXRlago=
Jan 03 2012
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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
Jan 03 2012