Your skill will accomplishwhat the force of many cannot PerlMonks

### comment on

 Need Help??

A little bench-marking can be helpful. For the case of converting an array to a hash where the array values become keys and the array index become values.

I've bench-marked the OP code as well as the variations presented in response, in addition I added my own solution to the problem (variation3). The clear winner is variation1.

```my %hash; @hash{ @array } = 0 .. \$#array;
```#!/usr/bin/env perl
use strict;
use warnings;

use Benchmark qw(:all);

my @array=qw(a b c d e f g h);

sub original {
my %hash;
for (my \$idx=0; \$idx<@array; \$idx++) { \$hash{\$array[\$idx]} = \$idx;}
}

sub variation1 {
my %hash;
@hash{ @array } = 0 .. \$#array;
}

sub variation2 {
my %hash = map { \$array[\$_] => \$_ } 0..\$#array;
}

sub variation3 {
my \$idx = 0;
my %hash = map { \$_ => \$idx++ } @array;
}

cmpthese(-10, {
'original' => sub{
original()
},
'variation1' => sub{
variation1()
},
'variation2' => sub{
variation2()
},
'variation3' => sub{
variation3()
},
});
results:
```               Rate variation2 variation3   original variation1
variation2 142570/s         --       -15%       -35%       -49%
variation3 168018/s        18%         --       -24%       -40%
original   220185/s        54%        31%         --       -21%
variation1 279147/s        96%        66%        27%         --

In reply to Re: better array to hash conversion by ruzam
in thread better array to hash conversion by perltux

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Are you posting in the right place? Check out Where do I post X? to know for sure.
• Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
• Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
• Want more info? How to link or How to display code and escape characters are good places to start.

Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2023-02-02 00:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?