in reply to optimization - exists should return a reference

There are two lines of though. One is that you're likely to need the value of the hash key after testing if it exists. The other is that, if you don't need it, but really just wanted to check if it exists, then you're loosing speed, not gaining it. Also, if all you really wanted was a bool, you just created and then destroyed a reference for nothing, which isn't exactly free.

The real solution would be common subexpression optimization, which is significantly more difficult.

You should benchmark exists (as it currently exists) vs. getting the value of a hash value, then consider usage patterns, and if it's worth it. Once you've got some numbers, talk to perl5-porters. Even better, once you've got some numbers and a patch...

You might also want to post to perl6-langauge about this -- since bool and ref context will be differencatable in perl6, you can get the best of both worlds. In fact, it could even return the value, but give "undef-but-true", etc, to give true results when the kv exists, but the value is false.


Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

  • Comment on Re: optimization - exists should return a reference

Replies are listed 'Best First'.
Re: Re: optimization - exists should return a reference
by Elian (Parson) on Jan 15, 2003 at 23:03 UTC
    The real solution would be common subexpression optimization, which is significantly more difficult.
    Even more than most people think. Not only is it a bit of a pain to do, and somwehat time consuming, but it potentially alters the semantics of the program. If a hash is tied, caching the return from exists, if exists returns a ref, changes a two-tie-hit to a one-tie-hit. While this may not necessarily be a bad thing, it is definitely a change in behaviour.
Re: Re: optimization - exists should return a reference
by John M. Dlugosz (Monsignor) on Jan 16, 2003 at 03:50 UTC
    My first thought was indeed common subexpression elimination. But Elian pointed out that this can't be done because you don't know at compile time that the hash dereferences don't have side effects (they may be tied or magic).

    So, to not evaluate the dereference twice, it's necessary to not write it twice. That's what led to this idea. I think it's consistant with other things in Perl such as how logical || returns the value rather than meer truth.

    —John