in reply to Re: sprintf vs. substr (for zero-padded values)
in thread sprintf vs. substr (for zero-padded values)

Ahh... Admittedly, I didn't run that code through the mill looking for bugs, only drew it up quickly to benchmark it. Good catch, now I guess I know why people use sprintf for this even though it's a bit slower.
  • Comment on Re: Re: sprintf vs. substr (for zero-padded values)

Replies are listed 'Best First'.
Re^3: sprintf vs. substr (for zero-padded values)
by tadman (Prior) on Jul 18, 2002 at 12:13 UTC
    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.
      Wow... ++tadman for discovering the flaw in my master plan, and for opening my eyes to how expensive calling a subroutine seems to be. Why is calling a sub so expensive?
        Why is calling a sub so expensive?
        You got to save state (and restore it when the sub returns). Furthermore, the lookup is done at runtime, not compiletime. After all, it's fine to have a call to a sub preceed the actual declaration - not to mention that AUTOLOAD would work if all was done at compile time.

        Abigail