ribasushi has asked for the wisdom of the Perl Monks concerning the following question:
And here are the results I get:use Benchmark qw(:all); my $a = 10; my $b = 20; cmpthese(-2, { 'Direct' => sub { my $c = $a+$b; }, 'Sub' => sub { my $c = add ($a, $b); }, 'Method' => sub { my $c = __PACKAGE__->meth_add ($a, $b); }, 'Method+sub' => sub { my $c = __PACKAGE__->meth_sub_add ($a, $b); }, 'Sub^2' => sub { my $c = add2 ($a, $b); }, 'Method^2' => sub { my $c = __PACKAGE__->meth2 ($a, $b); }, }); sub add { return $_[0] + $_[1]; } sub add2 { return add (@_); } sub meth_add { shift; return $_[0] + $_[1]; } sub meth_sub_add { shift; return add (@_); } sub meth2 { return $_[0] -> meth_add ( $_[1], $_[2] ); }
Rate Method^2 Method+sub Sub^2 Method Sub Direct
Method^2 500713/s -- -22% -37% -44% -58% -91%
Method+sub 643967/s 29% -- -19% -27% -46% -88%
Sub^2 797484/s 59% 24% -- -10% -33% -85%
Method 886331/s 77% 38% 11% -- -26% -84%
Sub 1191561/s 138% 85% 49% 34% -- -78%
Direct 5397078/s 978% 738% 577% 509% 353% --
Now I understand how method dispatch works and why it is slow, but I do not understand why subroutines suffer almost the same penalty. Is there some kind of perl compile flag, or some hidden optimization that can improve these numbers (which _really_ add up in a complex code flow)?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Performance issues with subroutines/methods
by shmem (Chancellor) on Jun 17, 2007 at 19:56 UTC | |
|
Re: Performance issues with subroutines/methods
by diotalevi (Canon) on Jun 17, 2007 at 21:18 UTC | |
by ysth (Canon) on Jun 18, 2007 at 01:37 UTC | |
by diotalevi (Canon) on Jun 18, 2007 at 01:45 UTC | |
|
Re: Performance issues with subroutines/methods
by ysth (Canon) on Jun 18, 2007 at 02:38 UTC | |
|
Re: Performance issues with subroutines/methods
by BrowserUk (Patriarch) on Jun 18, 2007 at 14:54 UTC | |
by fenLisesi (Priest) on Jun 19, 2007 at 06:56 UTC | |
by BrowserUk (Patriarch) on Jun 19, 2007 at 07:15 UTC | |
|
Re: Performance issues with subroutines/methods
by jbert (Priest) on Jun 18, 2007 at 13:39 UTC |