A quick Benchmark will show that this repeated concatenation is slower than sprintf:
#!/usr/local/bin/perl
use Benchmark;
my $var=13;
my $length=6;
timethese(100000, {
CONCAT=>\&concat,
SPRINTF=>\&spr_f,
});
sub concat {
my $a = $var;
while (length($a)<$length) {$a="0$a";}
}
sub spr_f {
my $a = $var;
sprintf("%0$length", $a);
}
Results:
Benchmark: timing 100000 iterations of CONCAT, SPRINTF...
CONCAT: 2 wallclock secs ( 1.53 usr + 0.00 sys = 1.53 CPU) @ 65
+359.48/s (n=100000)
SPRINTF: 0 wallclock secs ( 0.60 usr + 0.00 sys = 0.60 CPU) @ 16
+6666.67/s (n=100000)
UpdateOops, fixed the bug,
tye's right that it doesn't change the result much, but I didn't really want to return the correct value in concat() or make spr_f() extra fast, just wanted to compare the process to create the desired result.
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.