While refactoring some code I got to wondering about 'what is the fastest way to remove the first character in a string?' So I cobbled together some code to find out. I had been using
s/.//; but I am admittedly prone to regex abuse. I found the results to be a little surprising and wondered if anyone else had different entries for the putative horse race?
#!/perl/bin/perl
#
# bench.pl --
use strict;
use warnings;
use diagnostics;
use Benchmark qw(:all);
sub caseone {
$_ = '|0|0|0|0|0|0|';
s/.//;
}
sub casetwo {
$_ = '|0|0|0|0|0|0|';
substr($_,0,1) = '';
}
sub casethree {
$_ = '|0|0|0|0|0|0|';
$_ = reverse $_;
chop;
$_ = reverse $_;
}
sub casefour {
$_ = '|0|0|0|0|0|0|';
$_ = substr($_,1);
}
cmpthese(-5,{
'caseone' => 'caseone',
'casetwo' => 'casetwo',
'casethree' => 'casethree',
'casefour' => 'casefour',
});
And the results look like:
Rate caseone casethree casetwo casefour
caseone 293156/s -- -12% -21% -32%
casethree 331364/s 13% -- -10% -23%
casetwo 369954/s 26% 12% -- -14%
casefour 430979/s 47% 30% 16% --
--hsm
"Never try to teach a pig to sing...it wastes your time and it annoys the pig."
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.