http://qs1969.pair.com?node_id=502651


in reply to Accessors in xs

Testing object creation and 2 method-calls, gives a 25% speedup

use strict; use warnings; use Benchmark 'cmpthese'; use lib ('blib/lib', 'blib/arch'); use CMethods; use PerlMethods; my($x, $y); cmpthese( 200_000, { cMethods => sub { my $c = CMethods->new; $x = $c->x; $y = $c->y; }, PerlMethods => sub { my $c = PerlMethods->new; $x = $c->x; $y = $c->y; }, });
Rate PerlMethods cMethods PerlMethods 111297/s -- -17% cMethods 134771/s 21% -- Rate PerlMethods cMethods PerlMethods 111297/s -- -20% cMethods 139179/s 25% -- Rate PerlMethods cMethods PerlMethods 108460/s -- -22% cMethods 139179/s 28% --

Testing object creation and 200 method-calls (to lessen the overhead of creating the object), gives an impresive 78% speedup

use strict; use warnings; use Benchmark 'cmpthese'; use lib ('blib/lib', 'blib/arch'); use CMethods; use PerlMethods; my($x, $y); cmpthese( 50_000, { cMethods => sub { my $c = CMethods->new; for (1..100) { $x = $c->x; $y = $c->y; } }, PerlMethods => sub { my $c = PerlMethods->new; for (1..100) { $x = $c->x; $y = $c->y; } }, });
Rate PerlMethods cMethods PerlMethods 2933/s -- -44% cMethods 5220/s 78% -- Rate PerlMethods cMethods PerlMethods 2958/s -- -44% cMethods 5255/s 78% -- Rate PerlMethods cMethods PerlMethods 2949/s -- -44% cMethods 5246/s 78% --

Here's the code I used:

PerlMethods.pm
package PerlMethods; use strict; sub new { my ($pckg, $x, $y) = @_; my $self = { x => $x, y => $y }; return bless $self, $pckg; } sub x { my ($self) = @_; return $self->{x}; } sub y { my ($self) = @_; return $self->{y}; } 1;
CMethods.pm
package CMethods; use strict; our @ISA = qw(); our $VERSION = '0.01'; require XSLoader; XSLoader::load('CMethods', $VERSION); sub new { my ($pckg, $x, $y) = @_; my $self = { x => $x, y => $y }; return bless $self, $pckg; } 1;
CMethods.xs
#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" MODULE = CMethods PACKAGE = CMethods PROTOTYPES: DISABLE void x(self) HV *self PREINIT: SV **x; PPCODE: x = hv_fetch( self, "x", 1, 0 ); EXTEND(SP, 1); PUSHs(x ? *x : &PL_sv_undef); void y(self) HV *self PREINIT: SV **y; PPCODE: y = hv_fetch( self, "y", 1, 0 ); EXTEND(SP, 1); PUSHs(y ? *y : &PL_sv_undef);