Musing about the lack of enumerations in Perl and what best to use as "symbols", I benchmarked the speed of comparing numbers, strings, and refs (code below). As expected, numbers are faster. But most unexpectedly, refs are rather slow! I would have thought that it would be about the same as for a number, since it just compares addresses. Anybody know what the story is on this?

use strict; use warnings; use Benchmark 'cmpthese'; my ($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; } 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); } });
—John

In reply to 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.