AUTOLOAD vs tie in hash key validation

code

#!/usr/bin/perl
use strict;
use warnings;
use utf8;

use Benchmark ':all';

{   
    package Tie;
    use Tie::Hash;
    use parent -norequire, qw/Tie::StdHash/;
    sub FETCH {
        my ($self, $key) = @_;
        Carp::croak("Cannot retrieve unknown key: $key") unless exists $self->{$key};
        return $self->{$key};
    }
    sub TIEHASH {
        my $class = shift;
        my $default = shift;
        return bless {%$default}, $class;
    }
}

{   
    package My::AutoLoad;
    sub new {
        my ($class, $src) = @_;
        bless {%$src}, $class;
    }
    our $AUTOLOAD;
    sub AUTOLOAD {
        my $self = shift;
        my $class = ref $self;
        (my $meth = $AUTOLOAD) =~ s/$class\:://;
        Carp::croak("cannot retrieve unknown key: $meth") unless exists $self->{$meth};
        return $self->{$meth};
    }
    sub DESTROY { 1 }
}

my %hash;
tie %hash, "Tie", {foo => 'bar', baz => 'moge'};
my $hashref = \%hash;
$hashref->{foo} eq 'bar' or die;
eval { my $v = $hashref->{unknown} };
$@ or die $@;

my $al = My::AutoLoad->new({foo => 'bar', baz => 'moge'});
$al->foo eq 'bar' or die;
eval { $al->unknown };
$@ or die $@;

cmpthese(
    -1 => {
        tie => sub {
            $hashref->{foo};
        },
        autoload => sub {
            $al->foo
        },
    },
);

result

             Rate      tie autoload
tie      157827/s       --     -21%
autoload 199110/s      26%       --

Conclusion.

You should use autoload in most case. because It is faster and flexible.

Published: 2010-12-06(Mon) 14:40