Wondering if perl4 would run one of my RegExp-happy scripts faster than perl5 I had to roll my own chr() and thought I'd benchmark it against the builtin.

I was surprised to see that the chr() builtin was significantly slower than pack("C"). Even more surprised that the sub mychr was faster than the direct pack("C"). Can anyone explain why either of these is the case?

% perl5.8.0 use Benchmark; sub mychr { return pack("C", shift); } @array = @array = (0 .. 255) x 100; timethese(1000, { 'sub' => 'foreach (@array) { my $chr = chr($_) }', 'builtin' => 'foreach (@array) { my $chr = &mychr($_) }', 'direct' => 'foreach (@array) { my $chr = pack("C", $_) }', }); Benchmark: timing 1000 iterations of builtin, direct, sub... builtin: 156 wallclock secs (143.82 usr + 0.17 sys = 143.99 CPU) @ + 6.94/s (n=1000) direct: 53 wallclock secs (48.89 usr + 0.04 sys = 48.93 CPU) @ 20 +.44/s (n=1000) sub: 37 wallclock secs (31.16 usr + 0.03 sys = 31.19 CPU) @ 32 +.06/s (n=1000)

In reply to chr() suprisingly slow by sirhc

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.