Perl: the Markov chain saw | |
PerlMonks |
Efficient array element deletionby kennethk (Abbot) |
on Dec 04, 2008 at 22:52 UTC ( [id://728128]=perlquestion: print w/replies, xml ) | Need Help?? |
kennethk has asked for the wisdom of the Perl Monks concerning the following question: After reading Shift, Pop, Unshift and Push with Impunity!, a question occurred to me (purely academic). If I have a long array and my goal is to perform some test on each element and remove those elements that fail, what are the best ways to do it from CPU and memory standpoints? So one choice would be @array = grep(!/^\#/, @array) where presumably the grep operation has been heavily optimized for CPU time. However, this should create a temporary result array, which in turn could double my memory footprint. On the other extreme of the spectrum, I could say
but unless just about every entry is excised, that imposes a large performance toward the end of the operation. So the above-noted node inspired the following solution
My question is: would this ultimately have worse memory penalties than grep? It seems it must ultimately allocate enough memory at one end to accommodate the entire set, and then the interpreter/system cannot recover this memory since the variable is still allocated. Also, is there an even more clever way to do this I'm missing? Update:Following the notes by johngg and jwkrahn, I've corrected an error in my splice loop and learned something new about negative indices. Just because you tested code doesn't mean it did what you thought...
Back to
Seekers of Perl Wisdom
|
|