Subject: | Add SCALAR method |
Adding the SCALAR method would more than double the speed of conditions à la
if (%ixhash) {
...
}
See the attached benchmark script.
The implementation:
sub SCALAR {
scalar @{ $_[0]->[1] };
}
Note that currently scalar %ixhash would return undef for false and 1
for true. A normal hash usually returns 0 for false and some quotient
for true. With this implementation the return value would be 0 for false
and the number of keys for true.
Regards,
Slaven
Subject: | tie-ixhash-scalar.pl |
#!/usr/bin/perl -w
# -*- perl -*-
#
# $Id: $
# Author: Slaven Rezic
#
# Copyright (C) 2008 Slaven Rezic. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: slaven@rezic.de
# WWW: http://www.rezic.de/eserte/
#
use Benchmark qw(cmpthese);
use Tie::IxHash;
{
package Tie::MyIxHash;
use base qw(Tie::IxHash);
sub SCALAR {
scalar @{ $_[0]->[1] };
}
}
tie %ixhash, 'Tie::IxHash';
tie %myixhash, 'Tie::MyIxHash';
%ixhash = %INC;
%myixhash = %INC;
cmpthese(-1, {
without_SCALAR => sub {
if (%ixhash) {
# nop
}
},
with_SCALAR => sub {
if (%myixhash) {
# nop
}
},
}
);
__END__
Rate without_SCALAR with_SCALAR
without_SCALAR 159421/s -- -56%
with_SCALAR 358596/s 125% --