Re: Using Scalar::Util
[prev]
[thread]
[next]
[Date index for 2004/06/23]
Perrin Harkins wrote:
> Drew Taylor wrote:
>
>> How does this relate to Class::DBI? There are LOTS of checks in method
>> calls to make sure it is called either as an instance or class method.
>> They all use something like
>>
>> sub foo {
>> my $self = shift;
>> # only called as instance method
>> return unless ref $self;
>> }
>>
>> I propose that C::DBI should use blessed() instead since it's a better
>> check.
>
>
> You can check this pretty easilly without Scalar::Util by doing the Can
> can:
>
> return unless UNIVERSAL::can($self, 'can')
>
> That's how Template Toolkit does it. More complete than ref(), but also
> slower.
Just for curiosity, I benchmarked the 3 methods:
Perl 5.8.3 on FreeBSD 4.8-STABLE (pair.com) running on a Pentium 4 1800
MHz, 1024MB RAM.
script:
=======
#!/usr/bin/perl -w
use strict;
use Benchmark qw(:all);
use Scalar::Util qw(blessed);
my $count = 500000;
my $tests = {ref =>sub {my $self = bless {}, 'Foo'; ref $self; },
blessed=>sub {my $self = bless {}, 'Foo'; blessed $self; },
univ =>sub {my $self = bless {}, 'Foo';
UNIVERSAL::can($self, 'can') },
};
cmpthese($count, $tests);
timethese($count, $tests);
Results:
========
Rate univ blessed ref
univ 361582/s -- -16% -27%
blessed 429530/s 19% -- -13%
ref 492308/s 36% 15% --
Benchmark: timing 500000 iterations of blessed, ref, univ...
blessed: 1 wallclock secs ( 1.17 usr + 0.00 sys = 1.17 CPU) @
426666.67/s (n=500000)
ref: 2 wallclock secs ( 1.04 usr + 0.00 sys = 1.04 CPU) @
481203.01/s (n=500000)
univ: 0 wallclock secs ( 1.34 usr + 0.00 sys = 1.34 CPU) @
372093.02/s (n=500000)
So ref() is fastest (no surprise), but blessed is only 13% slower.
Anyway food for thought.
Drew
--
----------------------------------------------------------------
Drew Taylor * Web development & consulting
Email: drew@xxxxxxxxxx.xxx * Site implementation & hosting
Web : www.drewtaylor.com * perl/mod_perl/DBI/mysql/postgres
----------------------------------------------------------------