Today around 10:19pm, Bart Lateur hammered out this masterpiece:

: I, too, once used chop() to get the last character of a string, in my
: case to calculate a barcode check digit.
: 
:       while(my $digit = chop($barcode)) {
:           ...
:       }
: 
: The while loop should have continued until $barcode was empty, all
: digitis consumed. Well, the fact that "0" is false really spoilt it for
: me.

  my $code = '0924820342840';
  while ( length( $_ = chop $code ) > 0 ) {
    print $_;
  }
  print "\n";

I would be the first to say that this looks like a reasonable use for
chop(), I also know that in the Real World you wouldn't want to
destroy your bar code.  You would want to use it later.

Because of this, and because of the following benchmark, I can't say
that I would use chop() either.


  timethese( 1000000, {
  choping => sub {
    my $code = '0924820342840';
    while ( length( $_ = chop $code ) > 0 ) {
  #    print $_;
    }
  #  print "\n";
  },
  substr => sub {
    my $code = '0924820342840';
    foreach ( 1 .. length( $code ) ) {
  #    print substr $code, $_*-1, 1;
    }
  #  print "\n";
  }});


Benchmark: timing 1000000 iterations of choping, substr...
   choping: 38 wallclock secs (37.28 usr +  0.10 sys = 37.38 CPU) @ 26749.89/s 
(n=1000000)
    substr: 19 wallclock secs (17.53 usr +  0.07 sys = 17.60 CPU) @ 56818.18/s 
(n=1000000)

: The full story is: chop() is not a generic operator, but one
: specifically intended for one dedicated task: dropping the newline from
: a string read from a file. If you use it for anything else, it probably
: sooner or later will bite you. And it's not particularily good at what
: it *was* designed for, e.g. with a file not ending in a newline.

I'm sure there are other reasonable uses for chop() besides this ( I
can't think of any, funny I feel this way :) however, if the benchmark
is any idication of the speed of chop(), I am just going to use:

  substr $foo, -1;

from now on.  Of course, just to check:

  timethese( 10000000, {
  choping => sub {
    my $code = '0924820342840';
    my $last = chop $code;
  },
  substr => sub {
    my $code = '0924820342840';
    my $last = substr $code, -1;
  }});


Benchmark: timing 10000000 iterations of choping, substr...
   choping: 32 wallclock secs (31.15 usr +  0.08 sys = 31.23 CPU) @ 320170.76/s 
(n=10000000)
    substr: 34 wallclock secs (32.87 usr +  0.13 sys = 33.00 CPU) @ 303030.30/s 
(n=10000000)

Doesn't seem like that much gain from chop() to substr(), but it's
still a gain.  20k/s more...

-- 


print(join(' ', qw(Casey R. Tweten)));my $sig={mail=>'[EMAIL PROTECTED]',site=>
'http://home.kiski.net/~crt'};print "\n",'.'x(length($sig->{site})+6),"\n";
print map{$_.': '.$sig->{$_}."\n"}sort{$sig->{$a}cmp$sig->{$b}}keys%{$sig};
my $VERSION = '0.01'; #'patched' by Jerrad Pierce <belg4mit at MIT dot EDU>

Reply via email to