in reply to Re^2: foreach argument modification inside loop, followed by return from loop
in thread foreach argument modification inside loop, followed by return from loop
that was just proof-of-concept code
Understood, and thanks for posting your real code farther down the thread. Based on that, the relevant logic you have is this:
my $idx = 0; for my $j (@a) { if ($j == $target) { splice(@a, $idx, 1); last; } ++$idx; }
Which helps clarify what you're trying to do: remove an element from an array by value. I'm still far from convinced that there is any benefit to a splice/last approach, even based solely on the grounds that it's slower and more complex than something like this:
my $idx = firstidx { $_ == $target } @a; splice(@a, $idx, 1) if $idx >= 0;
Timing for 1e6 entries:
Rate for firstidx for 24.3/s -- -22% firstidx 31.1/s 28% --
Certainly in this case, the for approach seems clearly suboptimal (List::MoreUtils' XS code does essentially the same thing as the for loop, much faster and more cleanly). Results were similar with any array sizes where efficiency is likely to matter.
#!/usr/bin/env perl use 5.012; use warnings; use Benchmark qw/cmpthese/; use List::Util qw/shuffle/; use List::MoreUtils qw/firstidx/; my @for = 1..1e6; my @firstidx = 1..1e6; my @remove_for = shuffle @for; my @remove_firstidx = @remove_for; # Same search order # Use iteration count, not time, so we can verify results. cmpthese(100, { for => sub { my $target = pop @remove_for; my $idx = 0; for my $j (@for) { if ($j == $target) { splice(@for, $idx, 1); last; } ++$idx; } }, firstidx => sub { my $target = pop @remove_firstidx; my $idx = firstidx { $_ == $target } @firstidx; splice(@firstidx, $idx, 1) if $idx >= 0; }, }); # Sanity check: arrays are the same die "Array length mismatch" if @for != @firstidx; die "Content different" if grep { $for[$_] != $firstidx[$_] } 0..$#for +;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: foreach argument modification inside loop, followed by return from loop
by vsespb (Chaplain) on Jul 10, 2013 at 13:29 UTC | |
by rjt (Curate) on Jul 10, 2013 at 14:37 UTC | |
by vsespb (Chaplain) on Jul 10, 2013 at 14:57 UTC | |
by rjt (Curate) on Jul 10, 2013 at 22:13 UTC |