in reply to Re: Alternative of Push operation
in thread Alternative of Push operation
#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $N = 2_000_000; my @topush = ( "Hello array!", 123 ); my @pusharray; my @splicearray; my @splicearray2; my @forarray; $#splicearray = ($N * scalar @topush) - 1; sub pushit { push @pusharray, @topush; } my $sppos = 0; sub spliceit { splice @splicearray, $sppos, scalar @topush, @topush; $sppos += @topush; } sub spliceit2 { splice @splicearray2, @splicearray2, scalar @topush, @topush; } sub forit { for my $value (@topush) { $forarray[ ++$#forarray ] = $value; } } cmpthese( $N, { 'push' => \&pushit, 'splice' => \&spliceit, 'splice2' => \&spliceit2, 'for' => \&forit, } );
As awaited the for loop is the slowest way to do it. push is the fastest of all. Using splice is quite in between of both. The interesting and surprising thing is that splice is faster without pre-allocating the array ('splice2') then with ('splice').Rate for splice splice2 push for 484262/s -- -59% -67% -76% splice 1169591/s 142% -- -21% -42% splice2 1481481/s 206% 27% -- -27% push 2020202/s 317% 73% 36% --
The moral of this seems to be:
Perl build-ins are already very optimized - don't try to replace them with your own Perl code.
If you need something done which is covered by a build-in function - use it. And don't think about it. If you need more performance you are using the wrong programming language!
|
|---|