in reply to Re^4: Set Operators
in thread Set Operators

Just caught that one myself! :-)

I've updated my example - as it now shows, the 'xop' is not that much faster than just iterating over the array with a properly constructed 'for' loop. In fact, in this example, 'grep' has turned out to be the most consistent performer (but that might be because there is no overhead in creating a hash). Grep is probably fastest because it is coded directly in C, rather than including any extra Perl contructs. Just goes to show that you should always test and test again before you go proclaiming one method over another! :-) (Serves me right for trying to be a smart-ass!)

Cheers,

-- Dave :-)

Replies are listed 'Best First'.
Re^6: Set Operators
by Aristotle (Chancellor) on Oct 27, 2002 at 16:06 UTC

    Obviously, as this task is exactly what grep was made for. :-) Although there is some Perl construct involved - the callback you have to provide to grep.

    Remember that you have to iterate once over the array at least once - whatever you do. grep does nothing more than iterate - where the hash methods have to do a lot more work.

    This doesn't mean grep is the be-all end-all solution: if you need to check many values against the same set, then constructing the hash will quickly pay off as all subsequent lookups run in nearly constant time. Esp when the set is large and even more so when the values are typically absent more often than not, the overhead of building the hash will pay off rapidly.

    Efficiency can only be achieved with knowledge of an algorithm's expected input data.

    Makeshifts last the longest.

      This doesn't mean grep is the be-all end-all solution: if you need to check many values against the same set, then constructing the hash will quickly pay off as all subsequent lookups run in nearly constant time. Esp when the set is large and even more so when the values are typically absent more often than not, the overhead of building the hash will pay off rapidly.

      Indeed, this was the case I had in mind. I guess it comes down to which is more readable,

       my %items = map {$_ => 1} qw (one two three);

      or:

      my %hash; @hash{qw(one two three)} = ();

      I'm still not clear on why that last one works...