Last active
December 14, 2015 21:09
-
-
Save Stantheman/5149280 to your computer and use it in GitHub Desktop.
perl substr, verse substition, versus lvalue substring speed comparison using Benchmark. regular substr won by a larger margin than I thought, which makes me generally happy
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
# running 5.10.0, but according to http://perldoc.perl.org/perl5160delta.html#Performance-Enhancements, these benchmarks might be out of sync: | |
# Assignment to substr in void context is now more than twice its previous speed. Instead of creating and returning a special lvalue scalar that is then assigned to, substr modifies the original string itself. | |
# substr no longer calculates a value to return when called in void context. | |
Benchmark: running l_substr, sed, substring for at least 10 CPU seconds... | |
l_substr: 11 wallclock secs (10.30 usr + 0.01 sys = 10.31 CPU) @ 1455470.71/s (n=15005903) | |
sed: 10 wallclock secs (10.35 usr + 0.04 sys = 10.39 CPU) @ 433279.21/s (n=4501771) | |
substring: 11 wallclock secs (10.44 usr + 0.01 sys = 10.45 CPU) @ 2926646.89/s (n=30583460) | |
Rate sed l_substr substring | |
sed 433279/s -- -70% -85% | |
l_substr 1455471/s 236% -- -50% | |
substring 2926647/s 575% 101% -- |
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/env perl | |
use strict; | |
use warnings; | |
use Benchmark qw( timethese cmpthese ) ; | |
my $r = timethese( -10, { | |
sed => sub { | |
my $sed_str = "This is a sentence"; | |
$sed_str =~ s/ is/ isnt/; | |
}, | |
substring => sub { | |
my $substring_str = "This is a sentence"; | |
substr($substring_str, 5, 2, "isnt"); | |
}, | |
l_substr => sub { | |
my $l_str = "This is a sentence"; | |
substr($l_str, 5, 2) = "isnt"; | |
}, | |
} ); | |
cmpthese $r; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment