Comparing refs is fast, yes. Taking references isn't.

Try precomputing the references to $sym1-$sym4...

Of course, that still winds up being about the same speed as string refs. I suspect that's because the ref comparison has to compare the type of the ref as well as the pointer?

use strict; use warnings; use Benchmark 'cmpthese'; my ($sym1, $sym2, $sym3, $sym4); my ($sym1_r, $sym2_r, $sym3_r, $sym4_r)= \($sym1, $sym2, $sym3, $sym4); sub strings { if ($_[0] eq "yes") { return 1; } elsif ($_[0] eq "no") { return 0; } elsif ($_[0] eq "maybe") { return 2; } elsif ($_[0] eq "foo") { return 3; } return undef; } sub numbers { if ($_[0] == 42) { return 1; } elsif ($_[0] == 33) { return 0; } elsif ($_[0] == 99) { return 2; } elsif ($_[0] == 69) { return 3; } return undef; } sub refs { if ($_[0] == \$sym1) { return 1; } elsif ($_[0] == \$sym2) { return 0; } elsif ($_[0] == \$sym3) { return 2; } elsif ($_[0] == \$sym4) { return 3; } return undef; } sub quick_refs { if ($_[0] == $sym1_r) { return 1; } elsif ($_[0] == $sym2_r) { return 0; } elsif ($_[0] == $sym3_r) { return 2; } elsif ($_[0] == $sym4_r) { return 3; } return undef; } my $ref_r=\&refsl; cmpthese (0, { 'strings 2' => sub { strings ("no") }, 'strings 4' => sub { strings ("notfound") }, 'numbers 2' => sub { numbers (33) }, 'numbers 4' => sub { numbers (99999) }, 'refs 2' => sub { refs (\$sym2); }, 'refs 4' => sub { refs (\&refs); }, 'qrefs 2' => sub { quick_refs ($sym2_r); }, 'qrefs 4' => sub { quick_refs ($ref_r); }, });

--
Mike

In reply to Re: speed of comparisons of things by RMGir
in thread speed of comparisons of things by John M. Dlugosz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.