in reply to Re: Re: Zero Padding
in thread Zero Padding

You had a bug in spr_f() (you end up using a format of "%06" instead of "%06d"). That didn't seem to affect the speed much, though. You also don't return the correct value from concat() so I fixed that too. I made spr_f() a bit faster by eliminating the extra copy. This penalizes concat() since it is now the only one that needs the extra copy (oh well).

I added my favorite (that I learned from chip) and reran the benchmark:

#!/usr/bin/perl -w use strict; use Benchmark qw( cmpthese ); my $num= 13; my $wid= 6; sub concat { my $a= $num; $a= "0$a" while length($a) < $wid; $a; } sub spr_f { sprintf( "%0${wid}d", $num ); } sub sub_s { substr( "0"x$wid.$num, -$wid ); } cmpthese( -3, { CONCAT => \&concat, SPRINTF => \&spr_f, SUBSTR => \&sub_s, }); __END__ Your Results: Benchmark: timing 100000 iterations of CONCAT, SPRINTF... CONCAT: 65359.48/s SPRINTF: 166666.67/s Mine: Rate CONCAT SPRINTF SUBSTR CONCAT 98370/s -- -62% -66% SPRINTF 257009/s 161% -- -10% SUBSTR 286165/s 191% 11% --

Looks like the substr() is fastest.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re: (tye)Re: Zero Padding
by dkubb (Deacon) on Feb 03, 2001 at 08:33 UTC
    This edges out substr() in my benchmarks:

    my $padded = '0' x ($wid - length $num) . $num;

      And it doesn't have the perhaps significant disadvantage of my favorite substr method of truncating numbers that are too wide. ):

              - tye (but my friends call me "Tye")