Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: better array to hash conversion

by davido (Archbishop)
on Dec 11, 2012 at 18:41 UTC ( #1008366=note: print w/replies, xml ) Need Help??

in reply to better array to hash conversion

Another way of looking at the problem:

When you convert the array to a hash with keys as the array's values, and values as the array's indices, you pay the price for conversion once. Your subsequent lookups will be quite fast. But you do pay for it; the overhead of the hashing algorithm, combined with the O(n) time complexity of converting the entire array to a hash.

On the other hand, if all you're interested in is an occasional search that yields an index, you could use List::MoreUtils first_index function:

use List::MoreUtils 'first_index'; my @array = qw( a b c d e f g h ); my $found_ix = first_index{ $_ eq 'd' } @array; print "Found 'd' at $found_ix.\n"; __END__ output: Found 'd' at 3.

This avoids the one-time overhead of generating hash keys for the entire structure, and the per-search overhead of hash lookups. But now every lookup will be an O(n) operation. If you're doing a lot of lookups this is a net loss. If you're doing few lookups, it could be a win, which would have to be verified via benchmarking.

One nice thing about the first_index method is that its semantics are pretty clear. But if you're doing frequent lookups your original idea of using a hash lookup is good.


Replies are listed 'Best First'.
Re^2: better array to hash conversion
by karlgoethebier (Monsignor) on Dec 12, 2012 at 07:33 UTC

    Thank you very much and best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1008366]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2018-02-25 22:27 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (315 votes). Check out past polls.