Created
December 2, 2009 17:37
-
-
Save mpeters/247376 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 { | |
my $new_str = $str; | |
'X' x (length($new_str) - 4) . substr($new_str, -4); | |
}, | |
'regex w/replace' => sub { | |
my $new_str = $str; | |
$new_str =~ s/(\d+)(\d{4})/('X' x length $1) . $2/e; | |
}, | |
'regex' => sub { | |
my $new_str = $str; | |
$new_str =~ s/\d(?=\d{4})/X/g; | |
}, | |
} | |
); | |
} | |
=results | |
String of 6 characters | |
Rate regex w/replace regex length and substr | |
regex w/replace 248139/s -- -67% -82% | |
regex 740741/s 199% -- -46% | |
length and substr 1369863/s 452% 85% -- | |
String of 10 characters | |
Rate regex w/replace regex length and substr | |
regex w/replace 251889/s -- -40% -81% | |
regex 418410/s 66% -- -68% | |
length and substr 1298701/s 416% 210% -- | |
String of 20 characters | |
Rate regex w/replace regex length and substr | |
regex w/replace 207469/s -- -24% -84% | |
regex 273224/s 32% -- -79% | |
length and substr 1282051/s 518% 369% -- | |
=cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment