Here's the thing. It's not slower. It's actually faster, but your benchmark wasn't constructed properly. You used a constant, which I think Perl was optimizing away. Also, you were burying sprintf within a relatively expensive function call. Take a look at this:
use Benchmark qw[cmpthese];
sub one {
sprintf("%09d",@_);
}
sub two {
substr("000000000$_[0]",-9);
}
cmpthese(100, {
one => sub { for(0..10000) { $_ = one($_) } },
two => sub { for(0..10000) { $_ = two($_) } },
tre => sub { for(0..10000) { $_ = sprintf("%09d", $_) } },
});
__DATA__
Benchmark: timing 100 iterations of one, tre, two...
one: 12 wallclock secs (10.63 usr + 0.00 sys = 10.63 CPU) @ 9
+.41/s (n=100)
tre: 3 wallclock secs ( 3.38 usr + 0.00 sys = 3.38 CPU) @ 29
+.59/s (n=100)
two: 12 wallclock secs (11.08 usr + 0.00 sys = 11.08 CPU) @ 9
+.03/s (n=100)
Rate two one tre
two 9.03/s -- -4% -69%
one 9.41/s 4% -- -68%
tre 29.6/s 228% 214% --
You're correct in your assumption that
substr is faster, so long as the only number you need to process is "213" and you bury it in a subroutine call. You'll have to admit that in the real world users tend to ask for a little more functionality than that.
It would seem that
sprintf wins by a knockout.
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.