Nice. If I add some other possibilities:
PerlSubCall => sub {
my $c = PerlMethods->new;
for (1..100) {
$x = PerlMethods::x($c); $y = PerlMethods::y($c);
}
},
cSubCall => sub {
my $c = CMethods->new;
for (1..100) {
$x = CMethods::x($c); $y = CMethods::y($c);
}
},
Direct => sub {
my $c = PerlMethods->new;
for (1..100) {
$x = $c->{x}; $y = $c->{y};
},
Fields => sub {
my UsingFields $c = UsingFields->new;
for (1..100) {
$x = $c->{x}; $y = $c->{y};
}
}
I get these results:
Rate PerlMethods PerlSubCall cMethods cSubCall Direct
+ Fields
PerlMethods 1875/s -- -4% -64% -72% -80%
+ -80%
PerlSubCall 1951/s 4% -- -62% -70% -79%
+ -80%
cMethods 5160/s 175% 164% -- -22% -44%
+ -46%
cSubCall 6596/s 252% 238% 28% -- -29%
+ -31%
Direct 9242/s 393% 374% 79% 40% --
+ -4%
Fields 9597/s 412% 392% 86% 45% 4%
+ --
which (unsurprisingly) shows that, if you need a massive speedup, there's no alternative to accessing the members directly. For a final iota of speed you can use the
fields mechanism: the
UsingFields.pm module is:
package UsingFields;
use strict;
use fields qw(x y);
sub new {
my ($pckg, $x, $y) = @_;
my $self = fields::new($pckg);
$self->{x} = $x; $self->{y} = $y;
return bless $self, $pckg;
}
sub x {
my ($self) = @_;
return $self->{x};
}
sub y {
my ($self) = @_;
return $self->{y};
}
1;
Update: Be warned that fields no longer gives any speedup with the development version of perl, and won't in 5.10 either.