in reply to When to Use Object Oriented approach in Perl? (RFC)
Method calls are very slightly slower than function calls...
use v5.10; use strict; use warnings; use Benchmark qw( cmpthese ); sub Foo::bar { $_[0][0] or die } our $object = bless [1], "Foo"; cmpthese -1 => { "method call" => q[ $::object->bar ], "fun call" => q[ Foo::bar( $::object ) ], }; __END__ Rate method call fun call method call 4365983/s -- -15% fun call 5128108/s 17% --
This is because with a normal function call, Perl can figure out which function is being called at compile time. At run time, it just has to call the function. With a method call, Perl needs to figure out which method to call at run time, taking into account things like inheritance.
However, the problem is with these toy examples that they're not taking into account the fact that in a typical program factors like method dispatch are not a major bottleneck. In a script that does heavy number crunching, or lots of IO, or string processing, switching from method calls to function calls may help you shave 0.04 seconds off its three minute execution time, so in terms of "how do I optimize this script", it's barely worth thinking about.
In my previous example, try changing the sub definition to this:
sub Foo::bar { my $filename = sprintf('/tmp/%s.txt', ref $_[0]); open my $fh, '>', $filename or die($!); print $fh $_[0][0] or die($!); close $fh or die($!); 1 while unlink $filename; }
And watch that 17% difference disappear. Speed is really not an important factor in choosing an OO approach.
While there are some tasks for which a procedural, or functional approach is more warranted1, for most medium-to-large-scale tasks OO should be your default approach. A well-structured OO project should result in very readable, understandable, maintainable, and extensible code.
1 Imagine Scalar::Util or List::Util written in an OO style. No thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: When to Use Object Oriented approach in Perl? (RFC)
by ikegami (Patriarch) on Aug 01, 2014 at 12:07 UTC | |
by tobyink (Canon) on Aug 01, 2014 at 14:14 UTC | |
|
Re^2: When to Use Object Oriented approach in Perl? (RFC)
by thanos1983 (Parson) on Aug 01, 2014 at 12:56 UTC |