Short answer: if you are going to need this calculation
only once, use a loop. If you need to do this kind of
calculation all the times, refactor your code.
Here goes the longer explanation.
A loop is the fastest way to get the index of an array
item, if you need it only once. Getting that information
from a hash is faster, but filling that hash is not going to
be faster than a simple loop.
LOOP:
for (0 .. $#array) {
if ($array[$_] eq $searched) {
print "$searched found at $_ \n";
last LOOP;
}
}
Notice that this approach would find the first
occurrence of the item, therefore giving you that index.
Conversely, using a hash would give you the last
occurrence of the same item, unless you take it into
account.
For example, this will hold the last index of each
item.
my %hash;
$hash{array[$_]} = $_ for 0 .. $#array;
To get all the indices of each item,
you should do this, instead:
push @{ $hash{array[$_]} } , $_ for 0 .. $#array;
Now, for the long array, the one that you can't afford
to store into a hash, because it would more than double your
memory occupation.
If you are in such a situation, you can't build a hash,
and looping through the array is going to take long as well.
Therefore, you have to refactor your code, using a different
data structure or removing the need for knowing the index of
a given item. QED.
HTH |