use strict; use Benchmark 'cmpthese'; my $SQUARE; my $MAX_NUMBER = 1000; foreach my $number (4..$MAX_NUMBER) { my $square = $number * $number; $SQUARE->{$square} = 1; } my $string = q(59738219024971503664); cmpthese ( -1, { orig => \&orig, indx => \&windex } ); sub orig { my $total_length = 0; foreach my $square (keys %{$SQUARE}) { if ($string =~ /$square/) { my $length = length($square); $total_length += $length; } } return $total_length; } sub windex { my $string = q(59738219024971503664); my $total_length = 0; foreach my $square (keys %{$SQUARE}) { if ( index( $string, $square ) > -1 ) { my $length = length($square); $total_length += $length; } } return $total_length; } __END__ % perl sqs.pl Rate orig indx orig 100.0/s -- -91% indx 1067/s 967% --