I'm standardizing some libs for CPAN release and amazed at how much I switched between subs and 'use constant' for class variables

I know people are peculiar to each one, but thats not my question...

I decided to do a quick benchmark between the two and was surpised -- 'use constant' was significantly faster for use as class methods , 1/3 the time of calling a sub.

Does anyone know why? I was under the impression that use constant just creates a sub in the namespace -- so I expected it to have the same performance as using an explicitly defined subrouting. I was kind of shocked to see the difference in execution time.

The speed difference is negligble for most uses -- it took 10k calls to show the difference beyond a margin of error. but at 10 , 1k 10k, 100k and 1MM calls , the difference still is roughly 3x longer for an explicit sub than a 'use constant' defined sub.


In reply to OOP - Constant Vs. Subroutine by 2xlp

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.