Does D have too many features?

Timon Gehr timon.gehr at gmx.ch
Sun Apr 29 01:37:10 PDT 2012


On 04/29/2012 10:20 AM, Jonathan M Davis wrote:
> On Sunday, April 29, 2012 10:07:38 David Nadlinger wrote:
>> On Saturday, 28 April 2012 at 23:51:43 UTC, Jonathan M Davis
>>
>> wrote:
>>> But even just storing it in a local variable to use later
>>> could destroy the locality enough to defeat LDC's optimization.
>>
>> Huh? I can't think of a situation where a hash table lookup would
>> entail less indirections than dereferencing a pointer stored in a
>> register (resp. the stack, depending on scheduling).
>
> If you have something like
>
> if(key in aa)
> {
>      // lots of code
>      func(aa[key]);
> }
>
> the compiler is not necessarily going to be able to determine that the AA has
> not been changed such that aa[key] can use the same lookup that key in aa did
> rather than redoing the lookup. A prime example would be
>
> if(key in aa)
> {
>      foo(aa);
>      func(aa[key]);
> }
>
> The compiler doesn't necessarily know that foo won't remove key from aa, so it
> can't save the result of key in aa to reuse rather than calling aa[key],
> whereas the programmer could know that foo doesn't do anything to aa which
> would make a pointer to the element invalid and can guarantee that only one
> lookup occurs by doing
>
> if(auto value = key in aa)
> {
>      foo(aa);
>      func(value);
> }
>
> And that's just one case where the compiler can't make such an optimization
> but the programmer can. It's _far_ better iMHO to have in return a pointer
> than to rely on the compiler removing extraneous lookups.
>
> - Jonathan M Davis

Well, what if the programmer "knows" that foo does not change 'aa', but 
it actually does? Then there would possibly be a segmentation fault. 
This implies that the 'in' operator cannot be used in @safe code. (Or 
there would have to be a special case, that allows 'in' if the result is 
directly cast to bool.)


More information about the Digitalmars-d mailing list