Shipped Scalar::Util::Instance
Data::Util::is_instance()をベースに,MooseのTypeConstraint::Classに似たコードジェネレータを書いた。
#!perl -w use strict; use Test::More tests => 2; use Scalar::Util::Instance { for => 'Foo', as => 'is_a_Foo' }; my $foo = bless {}, 'Foo'; my $bar = bless {}, 'Bar'; ok is_a_Foo($foo); ok !is_a_Foo($bar); __END__ 1 .. 2 ok 1 ok 2
速度はData::Util::is_instance()と大差はなかったが,blessed($x) && $x->isa('Foo')
よりはずっと高速であり,まずまず成功といえる。
benchmark/full-benchmark.plの結果から抜粋:
# "is_a_Foo" は Scalar::Util::Instance # "blessed" は blessed($x) && $x->isa('Foo') # "noop" は比較用のサブルーチン sub noop {} # "is_instance" は Data::Util::is_instance($x, 'Foo') # "_INSTANCE" は Params::Util::_INSTANCE($x, 'Foo') $ perl benchmark/full-benchmark.pl Perl 5.10.1 on i686-linux Scalar::Util::Instance(XS)/0.001 Scalar::Util(XS)/1.21 Params::Util(XS)/1.00 Data::Util(XS)/0.54 For Foo=HASH(0x887f048) Rate _INSTANCE blessed is_instance is_a_Foo noop _INSTANCE 7385/s -- -57% -77% -79% -81% blessed 17300/s 134% -- -45% -51% -54% is_instance 31508/s 327% 82% -- -11% -17% is_a_Foo 35544/s 381% 105% 13% -- -6% noop 37959/s 414% 119% 20% 7% -- # ほかは省略
あとはこのコードをベースにMoose/Mouseのclass_typeを実装する。