I came across a rather cunning optimisation in perl 5.10 and it gave me a new respect for the hoops that perl jumps through to make the runtime more efficient.

What's the difference between these constructs (if $var1 and $var2 are lexicals)?:

sub { $_->{key1} == $var1 } sub { $_->{key2} == $var2 }

The answer is they're the same to perl. Despite the different fixed string and different variable name, both coderefs will end up as the same opcode tree, roughly looking like:

sub { $_->{$internal_sv_1} == $$internal_sv_2 }

Where the two internal SVs are stored on the scratchpad. Same opcode tree, different blanks.

Why does this matter? The beauty is that it doesn't, perl gets it right for you. I only came across it because of my hacking on my DBI layer that turns Perl into SQL. I had incorrectly cached the key and variable names during the parse and so looked up the wrong ones when given the second subref. By pointing to the scratchpad all was right with the world again.


In reply to Optimisation in 5.10 - clever by lukeross

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.