Monky Python has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks,

does anybody knows a faster solution to remove a single element from an array?

@mit2 = grep($_ ne $rname, @mit2);
The reason I'm asking is that I'm doing this in a nested loop and I'm a little bit worried about
the scaleability if the array mit2 is getting bigger.

MP

Replies are listed 'Best First'.
Re: remove element from array
by davorg (Chancellor) on Sep 11, 2001 at 16:55 UTC

    If there's a good chance that the element will be early on in the array, then something like this might be a bit faster.

    my $i; foreach $i (0 .. $#mit2) { last if $mit2[$i] eq $rname; } splice @mit2, $i;

    Oh, it also assumes that the element you want to lose only appears once in the array.

    --
    <http://www.dave.org.uk>

    Perl Training in the UK <http://www.iterative-software.com>

      Oh yes I forgot.
      I know the position of the element and the element appears only once.
      I tried splice and it's already a little bit faster.

      Thanks
      MP

Re: remove element from array
by George_Sherston (Vicar) on Sep 11, 2001 at 16:58 UTC
    do you know the index of the element you want to get rid of? And do you know roughly what the other elements are? If yes to both, you could alter $mit[$index] so that it was the "lowest" element, then sort and shift. So if you knew all the elements were non-negative integers,
    $mit[$index] = -1; shift sort @mit;
    I don't know what the overhead of sort is, but this certainly should save on memory.

    § George Sherston
      George,
      You cant use sort in void context. It doesn't mean anything. Ithink what you stated would have to be written like this:
      $mit[$inde]=-1; @mit=sort @mit; shift @mit;
      But as other posters have said its much more efficient to use splice().

      Yves
      --
      You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)