I was curious so I wrote a benchmark for this. (Please note that benchmarks must be interpreted correctly and are sometimes not very meaningful, see 588703.)
#!/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, } );
The results are very interesting:
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% --
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').

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!


In reply to Re^2: Alternative of Push operation by mscharrer
in thread Alternative of Push operation by mihirjha

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.