http://www.perlmonks.org?node_id=1080390


in reply to Re: Perl object memory overhead
in thread Perl object memory overhead

Indeed; writing all those getters and setters manually is inconvenient.

use strict; use warnings; use Benchmark qw(cmpthese); use Time::Limit qw(20); package MOOSE { use Moose; has a => ( reader => 'get_a', writer => 'set_a', isa => 'Int', traits => ['Counter'], handles => { adjust_a => 'inc' }, ); has b => ( reader => 'get_b', writer => 'set_b', isa => 'Int', ); has c => ( reader => 'get_c', writer => 'set_c', isa => 'Int', ); __PACKAGE__->meta->make_immutable; } package OO { use Scalar::Util qw( looks_like_number ); sub new { bless $_[1], $_[0] } sub get_a{ my( $o ) = @_; $o->{a} }; sub set_a{ my( $o, $v ) = @_; $o->{a} = $v };; sub get_b{ my( $o ) = @_; $o->{b} }; sub set_b{ my( $o, $v ) = @_; $o->{b} = $v };; sub get_c{ my( $o ) = @_; $o->{c} }; sub set_c{ my( $o, $v ) = @_; $o->{c} = $v };; sub adjust_a{ my( $o ) = @_; $o->set_a( $o->get_a() + 1 ) }; } my @AoH1 = map 'OO'->new({ a=>1, b=>2, c=>3 }), 1 .. 3e4; my @AoH2 = map 'MOOSE'->new({ a=>1, b=>2, c=>3 }), 1 .. 3e4; cmpthese -3, { OO => sub { $_->adjust_a for @AoH1 }, MOOSE => sub { $_->adjust_a for @AoH2 }, };
Rate OO MOOSE OO 3.47/s -- -47% MOOSE 6.56/s 89% --
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Replies are listed 'Best First'.
Re^3: Perl object memory overhead (Benchmark special case?)
by BrowserUk (Patriarch) on Mar 31, 2014 at 13:44 UTC

    Ooh! Do I spy a benchmark special case like the ones that compiler makers used to add to get good scores? :)

    isa => 'Int', traits => ['Counter'], handles => { adjust_a => 'inc' },

    What if you changed the increment to +33?

    Also, it would be really useful to see the timing of adjust_a() run on the 3e6 objects, along with memory consumption?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      There's this:

      handles => { adjust_a => [ 'inc', 33 ] },

      It's not as fast because the arrayref in handles results in a curried coderef, but not unacceptably slow either.

      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name