SPUG: re-size array

Colin Meyer cmeyer at helvella.org
Mon Oct 11 17:44:51 CDT 2004


On Mon, Oct 11, 2004 at 10:03:10PM +0000, Michael R. Wolf wrote:
> 
> 
> 
> > %hash = @array;
> > 
> > @even = keys %hash;
> > @odd  = values %hash;
> 
> Tricky!  I like it.
> 
> But beware. It only works if you don't care about the ordering of the
> @even or @odd arrays. If you merely need to consider them as sets
> (collections), this will work. Otherwise, the ordering has been lost
> by creating a hash out of it.

Also worth noting is that you will get a bogus undef in the @odd array,
if there were an odd number of elements in @array.

> 
> It'll probably take a not-so-insignificant amount of time/CPU to build
> that hash.

I wouldn't think so. Perl hashes are pretty speedy to use. But just to be
sure, here's a test of hashes vs iterating through the list:

        Rate iter hash
iter 11962/s   -- -14%
hash 13831/s  16%   --

Hashes 14% faster than iterating (at least by my cheap test).

-Colin.

#!/usr/bin/perl
                                                                                
use Benchmark ':all';
                                                                                
my @a = 1..100;
                                                                                
cmpthese( 100_000, { iter => \&oddeven_iterate, hash => \&oddeven_hash } );
                                                                                
sub oddeven_hash {
  my ( $o, $e, %h );
  %h = @a;
  $o = [ keys %h ];
  $e = [ values %h ];
  return $e, $o;
}
                                                                                
sub oddeven_iterate {
  my ( $o, $e );
  push @{ $_ % 2 ? $o : $e }, $a[$_] for 0..$#a;
  return $e, $o;
}


More information about the spug-list mailing list