Skip to content

Instantly share code, notes, and snippets.

@realdecisions
Created September 25, 2015 15:51
Show Gist options
  • Save realdecisions/87b1e77a3a4f85bf5cc5 to your computer and use it in GitHub Desktop.
Save realdecisions/87b1e77a3a4f85bf5cc5 to your computer and use it in GitHub Desktop.
Perl uniq array
#!perl
use Benchmark qw/cmpthese/;
use strict;
my @array = ( 'a', 'a', 'a', 'b', 'c', 'd', 'e', 'g', 'e', 'e', 'g', 'c' );
sub uniq_v1 {
my %tmp;
my @new_array = grep {
my $ret = 1;
if ( exists $tmp{$_} ) {
$ret = 0;
}
$tmp{$_} = 1;
$ret;
} @array;
return @new_array;
}
sub uniq_v1_1 {
my %tmp = map { $_ => 1; } @array;
return keys(%tmp);
}
sub good_uniq {
my %tmp;
@tmp{@array} = @array;
return keys(%tmp);
}
sub good_uniq_1 {
my %tmp;
@tmp{@array} = 1 x @array;
return keys(%tmp);
}
use Data::Dumper;
warn Dumper( [ uniq_v1() ], [ uniq_v1_1() ], [ good_uniq() ], [good_uniq_1] );
cmpthese(
1000000,
{ 'uniq_v1' => \&uniq_v1,
'uniq_v1_1' => \&uniq_v1_1,
'good_uniq' => \&good_uniq,
'good_uniq_1' => \&good_uniq_1
}
);
__DATA__
Rate uniq_v1 uniq_v1_1 good_uniq good_uniq_1
uniq_v1 189036/s -- -24% -49% -73%
uniq_v1_1 250000/s 32% -- -33% -64%
good_uniq 373134/s 97% 49% -- -46%
good_uniq_1 694444/s 267% 178% 86% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment