Dear Serene Monks,

My problem is this: I want to test membership in a small set, many thousands of times. The set is a constant and I want my program to enforce that fact -- e.g. I don't want to use a global variable, unless I can guarantee that it is constant.

But, I don't have the ability to install and use Readonly::XS on my system.

My first try:

sub IsMember { my %Set = ( 'age' => 1, 'old' => 1, 'years' => 1); return $Set{$_[0]}; }

This seems to work okay, but profiling shows a significant amount of time in this subfunction (about 11 percent of my total run time.)

I also tried the same thing with a closure, just in case the %Set was being created on the stack each time:

{ my %Set = ( 'age' => 1, 'old' => 1, 'years' => 1); sub IsMember { return $Set{$_[0]}; } }
I also tried a regex, but still no significant speedup:

sub IsMember { return $_[0] =~ m/age|old|years/; }
I want to use a global constant hash and then access it directly (instead of through a function wrapper). But I cannot figure this out. I have perl 5.6.1 (and again, Readonly:XS is not an option at this time.) If no speedup can be expected - any suggestions on the best implementation of a constant hash (given my constraints) would be enormously helpful. - Student

In reply to Fastest way to test membership in a constant set by Anonymous Monk

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.