[Chicago-talk] Performance, and using a hash in a regex

Steven Lembark lembark at wrkhors.com
Fri Jul 14 16:59:47 PDT 2006

> 1) Don't.
> 2) (for experts) Don't yet.
> 3) Profile first.

Depends on what you're optimizing.

In most cases reasonably "clean" code will run well in
Perl. For example you COULD use:

  my $lookfor = shift;

  my $found = '';

  for my $key ( sort keys %hash )
    if( $key = $lookfor )
      $found = $hash{ $key };

      last VALUE

or you could do something more like:

  my $a = $hash{ $lookfor };

it doesn't take benchmarking to decide that the former
should be replaced. Frankly, if I see anything like

    my $a = 6;
    my $b = 7;

    my $sum = $a;

    for( my $i = 0 ; $i < $b ; ++$i )
      $sum = $sum + 1;

    $a = $sum;

I'll probably replace it with

  $a += $b;

without thinking much about it.

Using for my $value ( @ary ) instead of for my $i ( 0 ..
$#ary ) to iterate items where the index is not of
interest is another optimization that usually makes
the code look better. You'd probably find that
for( my $i = 0 ; $i < @ary ; ++$i ){ my $value = $arr[ $i ]; ...
} can be optimized to an internal iterator if you aren't
using $i for anything.

Most of these changes would be made in the interest of
"code cleanup" not speed, but they would tend to speed
up the code (however little).

So, you are probably better off optimizing the code
quality early in the process by developing data structures
that really reflect the data being processed or operations
that handle the data in least-convoluted ways.

Adding sufficient documentation and comments can save you
more runtime than anything else I've seen, with negligable
execution overhead. I'd suggest you optimize them for
coverage and comprehension without benchmarking your code
at all.

Steven Lembark                                         85-09 90th Street
Workhorse Computing                                  Woodhaven, NY 11421
lembark at wrkhors.com                                      +1 888 359 3508

More information about the Chicago-talk mailing list