in reply to Alternative of Push operation

From where "do we know" that the push operation is costly? Compared with what? Because it's a perl build-in it's already highly optimized C code so I don't think that any Perl code can be more efficient.
If you look in perldoc -f push:
[push @ARRAY, LIST] Has the same effect as for $value (LIST) { $ARRAY[++$#ARRAY] = $value; } but is more efficient.
IMHO the best way to make your code more efficient, i.e. less-costly, is to recode you script so it's doesn't need a push operation any more.

The most expensive thing with push might be the (re-)allocation of new memory, so if you would initialize the array with the final size at the start, e.g. $#array = 1000;, and use splice instead of push then you might save time. Please post a compare benchmark here if you code that.

Replies are listed 'Best First'.
Re^2: Alternative of Push operation
by mscharrer (Hermit) on Apr 28, 2008 at 12:35 UTC
    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.) 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!