使用'exists'进行额外的哈希查找?

时间:2009-06-10 18:30:00

标签: performance perl hash lookup exists

我有时会访问这样的哈希:

if(exists $ids{$name}){
    $id = $ids{$name};
}

这是好习惯吗?我有点担心它包含两个查找,其中一个应该完成。有没有更好的方法来检查存在并分配值?

6 个答案:

答案 0 :(得分:10)

通过exists核对,可以防止自动生成。请参阅Autovivification : What is it and why do I care?

更新:正如trendels所指出的那样,自动生成无法在您发布的示例中发挥作用。我假设实际代码涉及多级哈希。

以下是插图:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my (%hash, $x);

if ( exists $hash{test}->{vivify} ) {
    $x = $hash{test}->{vivify}->{now};
}

print Dumper \%hash;

$x = $hash{test}->{vivify}->{now};

print Dumper \%hash;

__END__


C:\Temp> t
$VAR1 = {
    'test' => {}
};
$VAR1 = {
    'test' => {
        'vivify' => {}
    }
};

答案 1 :(得分:1)

您可以使用以下一次查找来执行此操作:

$tmp = $ids{$name};
$id = $tmp if (defined $tmp);

但是,除非我看到那是一个瓶颈,否则我不会打扰

答案 2 :(得分:1)

你可以使用apply Hash::Util的lock_keys来表示哈希值。然后在评估中执行您的作业。

#!/usr/bin/perl
use Hash::Util qw/lock_keys/;

my %a = (
    1 => 'one',
    2 => 'two'
);

lock_keys(%a);

eval {$val = $a{2}};     # this assignment completes
eval {$val = $a{3}};     # this assignment aborts
print "val=$val\n";      # has value 'two'

答案 3 :(得分:0)

如果它不是多级哈希,你可以这样做:

$id = $ids{$name} || 'foo';

或者如果$ id已经有值:

$id ||= $ids{$name};

其中'foo'是默认值或直通值。如果它是一个多级哈希,你可以使用'exists'来避免线程中前面讨论的自动生成,或者如果autovivification不会成为问题就不使用它。

答案 4 :(得分:0)

如果我想要高性能,我习惯于在想要创建散列时写这个习惯用语:

my %h;
for my $key (@some_vals) {
  ...
  $h{$key} = undef unless exists $h{$key};
  ...
}

return keys %h;

此代码比常用的$h{$key}++快一点。 exists避免无用的分配,undef避免分配值。最适合您的是:基准测试!我想exists $ids{$name}$id=$ids{$name}快一点,如果你有很大的遗漏率,那么你的版本可能比赋值和测试更快。

例如,如果我想要快速设置交集,我会写这样的东西。

sub intersect {
  my $h;
  @$h{@{shift()}} = ();
  my $i;
  for (@_) {
    return unless %$h;
    $i = {};
    @$i{grep exists $h->{$_}, @$_} = ();
    $h = $i;
  }
  return keys %$h;
}

答案 5 :(得分:0)

在这种情况下,性能并不重要,请参阅“Devel :: NYTProf”。 但要回答你的问题:

如果散列中的值不存在,则“存在”非常快

if(exists $ids{$name}){
    $id = $ids{$name};
}

但如果确实存在,则完成第二次查找。 如果该值可能存在,那么只进行一次查找会更快

$id = $ids{$name};
if($id){
    #....
}

从perl邮件列表中查看这个小标准。

#!/usr/bin/perl -w
use strict;
use Benchmark qw( timethese );

use vars qw( %hash );
@hash{ 'A' .. 'Z', 'a' .. 'z' } = (1) x 52;

my $key = 'xx';
timethese 10000000, {
        'defined' => sub {
                if (defined $hash{$key}) { my $x = $hash{$key}; return $x; };
                return 0;
        },
        'defined_smart' => sub {
                my $x = $hash{$key};
                if (defined $x) {
                        return $x;
                };
                return 0;
        },
        'exists' => sub {
                if (exists $hash{$key}) { my $x = $hash{$key}; return $x; };
                return 0;
        },
        'as is' => sub {
                if ($hash{$key}) { my $x = $hash{$key}; return $x; };
                return 0;
        },
        'as is_smart' => sub {
                my $x = $hash{$key};
                if ($x) { return $x; };
                return 0;
        },

};

使用不存在的键('xx')表示'exists'是赢家。

Benchmark: timing 10000000 iterations of as is, as is_smart, defined, defined_smart, exists...
     as is:  1 wallclock secs ( 1.52 usr +  0.00 sys =  1.52 CPU) @ 6578947.37/s (n=10000000)
as is_smart:  3 wallclock secs ( 2.67 usr +  0.00 sys =  2.67 CPU) @ 3745318.35/s (n=10000000)
   defined:  3 wallclock secs ( 1.53 usr +  0.00 sys =  1.53 CPU) @ 6535947.71/s (n=10000000)
defined_smart:  3 wallclock secs ( 2.17 usr +  0.00 sys =  2.17 CPU) @ 4608294.93/s (n=10000000)
    exists:  1 wallclock secs ( 1.33 usr +  0.00 sys =  1.33 CPU) @ 7518796.99/s (n=10000000)

使用存在的密钥('x')表示'as is_smart'是赢家。

Benchmark: timing 10000000 iterations of as is, as is_smart, defined, defined_smart, exists...
     as is:  3 wallclock secs ( 2.76 usr +  0.00 sys =  2.76 CPU) @ 3623188.41/s (n=10000000)
as is_smart:  3 wallclock secs ( 1.81 usr +  0.00 sys =  1.81 CPU) @ 5524861.88/s (n=10000000)
   defined:  3 wallclock secs ( 3.42 usr +  0.00 sys =  3.42 CPU) @ 2923976.61/s (n=10000000)
defined_smart:  2 wallclock secs ( 2.32 usr +  0.00 sys =  2.32 CPU) @ 4310344.83/s (n=10000000)
    exists:  3 wallclock secs ( 2.83 usr +  0.00 sys =  2.83 CPU) @ 3533568.90/s (n=10000000)