Fastest Way of Accessing Entries in an AA

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 9 01:40:35 PST 2015


On Friday, January 09, 2015 07:51:27 Foo via Digitalmars-d-learn wrote:
> On Friday, 9 January 2015 at 06:18:53 UTC, Jonathan M Davis via
> Digitalmars-d-learn wrote:
> > On Friday, January 09, 2015 00:20:07 Foo via
> > Digitalmars-d-learn wrote:
> >> You know, that you kan reuse the result of the in operator by
> >> AAs?
> >>
> >> example:
> >>
> >> auto ptr = key in aa;
> >> ptr ? *ptr : ValueType.init
> >
> > This idiom is quite common:
> >
> > if(auto ptrToValue = key in aa)
> > {
> > }
> >
> > though I'm not sure that that quite fits in with what Nordlow
> > seems to be
> > trying to do with init. aa.get probably does a better job of
> > that, though
> > looking at the implementation for get, it's basically doing
> > what you're
> > suggesting:
> >
> > auto p = key in aa;
> > return p ? *p : defaultValue;
> >
> > though that has the downside of using a lazy parameter for the
> > default
> > value, which is convenient but doesn't do great things for
> > performance.
> >
> > - Jonathan M Davis
> I just wasn't sure that he knows about it.

Oh, he might not have known about it (certainly, the fact that he called in
and then [] in his origanal code implies that he didn't), and it was
definitely useful to tell him. My point was simply that get applies better
for his use case than using in directly. In general though, in is of _far_
more use than [], precisely because it combines asking whether the element
is there and getting it into one command. Personally, I pretty much never
use [] on AAs.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list