[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] !fwp: weird behavior with sort and unique-ing



* Yitzchak Scott-Thoennes (sthoenna@efn.org) [000121 02:32]:
> Andy Lester <andy@petdance.com> wrote:
> >
> >Item 4.6 in the Perl Cookbook goes into myriad ways to do it...
> 
> Which of course not everybody has.

Maybe not, but everyone *does* have perlfaq4:
  "How can I remove duplicate elements from a list or array?"



> My favorite way is:
> 
> sub uniq(@) {
>    my %seen;
>    grep !$seen{$_}++, @_
> }

Fun (fcdof) maybe, but slow.

And Austin, I have REALLY bad news for you.


__CODE__

use Benchmark;

sub uniq1(@) {
  my %s;
  @s{@_} = ();
  keys %s
}

sub uniq2(@) { # Yitzchak's version
  my %seen;
  grep !$seen{$_}++, @_
}

sub uniq3 { # Austin's version
  keys %{{ map {($_,undef)} @_ }};
}

my @a = (
  1 .. 128_000,
  1 ..  32_000,
  1 ..   8_000,
  1 ..   2_000
);

timethese( 1, {
  uniq1 => sub { my @b = uniq1(@a) },
  uniq2 => sub { my @b = uniq2(@a) },
  uniq3 => sub { my @b = uniq3(@a) },
});


__OUTPUT__

uniq1:   1.68 usr  secs
uniq2:   4.42 usr  secs
uniq3: 349.05 usr  secs

__END__

-- 
John Porter

"There are people who have fun studying the C++ spec for
literally seconds on end, I'm sure..."    John Vlissides


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe