in reply to list to LoL
I've done some quick benchmarking and all 3 of the methods posted so far are very equivalent when it comes to performance (tests below are on a 1000 element array arranging it into sub-arrays of 5 elements each)use Data::Dumper; my @a=(1..100); my @a3=reform_list(3,@a); print Dumper(@a3); my @a4=reform_list(4,@a); print Dumper(@a4); sub reform_list{ my $size=shift; my @list=@_; my @nlist=(); my $max=int(scalar(@list)/$size); for(my $c=0;$c<=$max;$c++){ my $a=$c*$size; my $b=($c+1)*$size-1; if($b>=scalar(@list)){ $b=scalar(@list)-1; } if($a<=$b){ push @nlist,[@list[$a..$b]]; } } return @nlist; }
| submitter | benchmark |
|---|---|
| adam | 6 wallclock secs ( 5.59 usr + 0.00 sys = 5.59 CPU) @ 894.45/s (n=5000) |
| lhoward | 6 wallclock secs ( 5.79 usr + 0.00 sys = 5.79 CPU) @ 863.56/s (n=5000) |
| swiftone | 6 wallclock secs ( 5.71 usr + 0.00 sys = 5.71 CPU) @ 875.66/s (n=5000) |
I've managed to clean up my code a little (though these changes didn't make it any faster). It doesn't look quite as ugly and still handles the fencepost conditions properly.
sub reform_list{ my $size=shift; my @list=@_; my @nlist=(); my $list_size=scalar(@list); my $c; my $stop=int($list_size/$size)*$size; for($c=0;$c<$stop;$c+=$size){ push @nlist,[@list[$c..($c+$size-1)]]; } if($c<$list_size){ push @nlist,[@list[$c..($list_size-1)]]; } return @nlist; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: Re: list to LoL
by princepawn (Parson) on Jun 02, 2000 at 22:39 UTC | |
by ZZamboni (Curate) on Jun 02, 2000 at 22:45 UTC |