Search code examples
type-conversioncomparisonraku

What is the most efficient operator to compare any two items?


Frequently I need to convert data from one type to another and then compare them. Some operators will convert to specific types first and this conversion may cause loss of efficiency. For instance, I may have

my $a, $b = 0, "foo"; # initial value
$a = (3,4,5).Set;     # re-assign value
$b = open "dataFile"; # re-assign value

if $a eq $b { say "okay"; } # convert to string
if $a == 5 { say "yes"; }   # convert to number
if $a == $b {} # error, Cannot resolve caller Numeric(IO::Handle:D: );

The operators "eq" and "==" will convert data to the digestible types first and may slow things down. Will the operators "eqv" and "===" skip converting data types and be more efficient if data to be compared cannot be known in advance (i.e., you absolutely have no clue what you are going to get in advance)?


Solution

  • Both === and eqv first check whether the operands are of the same type, and will return False if they are not. So at that stage, there is no real difference between them.

    The a === b operator is really short for a.WHICH eq b.WHICH. So it would call the .WHICH method on the operands, which could be expensive if an operand is something like a really large Buf.

    The a eqv b operator is more complicated in that it has special cased many object comparisons, so in general you cannot say much about it.

    In other words: YMMV. And if you're really interested in performance, benchmark! And be prepared to adapt your code if another way of solving the problem proves more performant.