I'm afraid your benchmark left room for improvement, KM:
use Benchmark; $string = "hello world I am a string of some sort of length" +; timethese(-1, { "match" => sub { ($char) = $string =~ /^.{4}(.)/;}, "unpack" => sub { ($char) = unpack("x4 A1", $string);}, "substr" => sub { ($char) = substr($string,4,1);}, "silly" => sub { my $string2 = $string; $char = chop $s +tring2 while length $string2 >= 4;}, #note the local });
Which gave somewhat more expected results:
Benchmark: running match, silly, substr, unpack, each for at least 1 C +PU seconds... match: 3 wallclock secs ( 1.00 usr + 0.02 sys = 1.02 CPU) @ 18 +0382.35/s (n=183990) silly: 4 wallclock secs ( 1.15 usr + 0.09 sys = 1.24 CPU) @ 17 +341.13/s (n=21503) substr: 2 wallclock secs ( 1.00 usr + 0.05 sys = 1.05 CPU) @ 94 +4029.52/s (n=991231) unpack: 2 wallclock secs ( 1.02 usr + 0.06 sys = 1.08 CPU) @ 36 +2192.59/s (n=391168)
Nevertheless, I'm suprised at the speed of silly. Can anybody explain why eating that string is faster than unpack, even if the string has some length?

Cheers,

jeroen
"We are not alone"(FZ)
Update: Ouch! Fixed... silly is the slowest, and the universe is back to normal :-)
The last benchmarks were recorded when my CPU hit a load of 4.63, so they may be a little distorted ;-)


In reply to Re:{3} Concatenation ... Strings by jeroenes
in thread Changing a character in the middle of a word (was: Concatenation ... Strings) by Zerhash

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.