Skip to content

Instantly share code, notes, and snippets.

@latk
Last active December 23, 2015 01:09
Show Gist options
  • Save latk/6558400 to your computer and use it in GitHub Desktop.
Save latk/6558400 to your computer and use it in GitHub Desktop.
Benchmarking 3rd element removal from large arrays
use 5.018; use strict; use warnings; use Benchmark ':all';
cmpthese $ARGV[0] => {
grep => \&with_grep,
grep_light => \&with_grep_light,
splice => \&with_splice,
slice => \&with_slice,
copy => \&with_copy,
};
sub with_grep {
my @testlist = qw (helloworld sessions first.cgi login localpcs depthhashes.cgi search view macros plugins)x$ARGV[1];
my $i = 0;
@testlist = grep { ++$i % 3 } @testlist;
}
sub with_grep_light {
my @testlist = qw (helloworld sessions first.cgi login localpcs depthhashes.cgi search view macros plugins)x$ARGV[1];
my $i = 0;
@testlist = grep ++$i % 3, @testlist;
}
sub with_slice {
my @testlist = qw (helloworld sessions first.cgi login localpcs depthhashes.cgi search view macros plugins)x$ARGV[1];
@testlist = @testlist[ grep { $_ % 3 } 0..$#testlist ];
}
sub with_splice {
my @testlist = qw (helloworld sessions first.cgi login localpcs depthhashes.cgi search view macros plugins)x$ARGV[1];
for (my $i = 2; $i < $#testlist; $i += 2) {
splice @testlist, $i, 1;
}
}
sub with_copy{
my @testlist = qw (helloworld sessions first.cgi login localpcs depthhashes.cgi search view macros plugins)x$ARGV[1];
my @output;
# pre-extend the array for fewer reallocations
$#output = @testlist * 2/3;
@output = ();
for (my $i = 0; $i < @testlist; $i += 3) {
push @output, @testlist[$i, $i+1];
}
}
__END__
Example timings
$ perl -v
This is perl 5, version 18, subversion 1 (v5.18.1) built for i686-linux-thread-multi-64int
...
$ time perl test.pl 5E3 100
Rate slice grep grep_light copy splice
slice 785/s -- -11% -11% -16% -34%
grep 882/s 12% -- -0% -5% -26%
grep_light 885/s 13% 0% -- -5% -26%
copy 929/s 18% 5% 5% -- -22%
splice 1196/s 52% 36% 35% 29% --
real 0m27.579s
user 0m27.382s
sys 0m0.020s
$ time perl test.pl 5E2 1000
Rate splice slice grep_light grep copy
splice 41.9/s -- -36% -44% -44% -50%
slice 65.1/s 55% -- -13% -13% -23%
grep_light 74.7/s 78% 15% -- -0% -11%
grep 74.9/s 79% 15% 0% -- -11%
copy 84.0/s 101% 29% 12% 12% --
real 0m39.817s
user 0m39.078s
sys 0m0.040s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment