#!/usr/bin/perl use strict; use warnings; use Moose; use Benchmark qw( cmpthese ); package MyImmuClass; use Moose; sub setsize { my $self= shift; $self->{size}= shift; } has 'size',is => 'rw', isa => 'Int'; __PACKAGE__->meta->make_immutable; package MyClass; use Moose; sub setsize { my $self= shift; $self->{size}= shift; } sub getsize { my $self= shift; $self->{size}; } has 'size',is => 'rw', isa => 'Int'; package main; my $obj= MyClass->new; my $immuobj= MyImmuClass->new; my $x; my %tests = ( Moose => sub { $x= $obj->size; }, 'hash access' => sub { $x= $obj->{size}; }, MooseImmu => sub { $x= $immuobj->size; }, accessor => sub { $x= $obj->getsize } ); cmpthese(-3, \%tests); %tests = ( Moose => sub { $obj->size(21); }, MooseImmu => sub { $immuobj->size(21); }, 'hash access' => sub { $obj->{size}=20; }, accessor => sub { $obj->setsize(22); } ); cmpthese(-3, \%tests); #------------------------------------------------------ Rate MooseImmu Moose accessor hash access MooseImmu 1505277/s -- -1% -2% -82% Moose 1517026/s 1% -- -2% -82% accessor 1542411/s 2% 2% -- -81% hash access 8232304/s 447% 443% 434% -- Rate Moose MooseImmu accessor hash access Moose 413580/s -- -1% -69% -92% MooseImmu 419426/s 1% -- -69% -91% accessor 1335932/s 223% 219% -- -73% hash access 4874075/s 1079% 1062% 265% --
As you can see, no speedup at all. The only speedup I did find was with Introspection, 'does' was 4 times faster now, but still 26 times slower than 'can', the duck typing alternative.
make_immutable should make accessors faster through 'inlining'. The tests seem to show that either this happens anyway or it doesn't work. My question is: Which one and why?
PS: If anyone is astonished that Moose is slower than an accessor on write, he should take into account that there is parameter checking built in
UPDATE:
FunkyMonk: Ah, the information I looked at was for an older version of Moose. CASE CLOSED. Explanation found
zwon, thanks for the debugging, corrected. Your observation is also quite probable, see my PS which makes the same point. Interestingly the speed is slightly better if 'Str' is used, but still with a big gap to the non-moose accessor, so even with Str there is some (unnecessary?) checking going on
In reply to Moose immutable speedup? by jethro
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |