Skip to content

Instantly share code, notes, and snippets.

@mpeters
Created December 2, 2009 17:33
Show Gist options
  • Save mpeters/247372 to your computer and use it in GitHub Desktop.
Save mpeters/247372 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use Benchmark qw(:all);
my @strings = (123456, 1234567890, 1234567890123456);
foreach my $str (@strings) {
print "\nString of " . length($str) . " characters\n";
cmpthese(
1000000,
{
'length and substr' => sub {
'X' x (length($str) - 4) . substr($str, -4);
},
'regex w/replace' => sub {
$str =~ s/(\d+)(\d{4})/('X' x length $1) . $2/e;
},
'regex' => sub {
$str =~ s/\d(?=\d{4})/X/g;
},
}
);
}
=results
String of 6 characters
Rate length and substr regex regex w/replace
length and substr 2127660/s -- -21% -83%
regex 2702703/s 27% -- -78%
regex w/replace 12500000/s 487% 362% --
String of 10 characters
Rate length and substr regex regex w/replace
length and substr 2222222/s -- -16% -84%
regex 2631579/s 18% -- -82%
regex w/replace 14285714/s 543% 443% --
String of 20 characters
Rate regex w/replace regex length and substr
regex w/replace 775194/s -- -51% -62%
regex 1587302/s 105% -- -22%
length and substr 2040816/s 163% 29% --
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment