Hello all,

I am using flyweight objects (i.e. the objects are blessed scalars which are keys of a lexical hash), which have resource-intensive methods that don't take any arguments.

I sometimes have a way to get pre-computed values for many of these methods.

I want to do two things :
  1. Be able to tell the objects what the return values for these methods should be, so that the methods don't have to be called sometimes.
  2. Memoize any calls to these methods (on an instance level), so that the methods don't do the resource-intensive operations multiple times.
The way I've done this is as follows (_get, _set, and _is_set are methods that get, set or check the attribute of the object by looking in the lexical hash) :
# In the various classes : __PACKAGE__->setupMemoizedSubs( methodname => sub { my $self = shift; #... do resource-intensive stuff .. }, anothermethod => sub { ... }, ) # In a common base class : sub setupMemoizedSubs { my ($class,%args) = @_; no strict 'refs'; while (my ($name,$sub) = each %args) { my $private_element = "__memoized_$name"; *{"${class}::$name"} = sub { my $self = shift; $self->_set($private_element => $_[0]) if @_==1; return $self->_get($private_element) if $self->_is_set($private_element); $self->_set($private_element => $sub->($self)); $self->_get($private_element); }; } use strict 'refs'; } # Somewhere else $object->methodname("pre-computed value"); # set the value $object->methodname(); # Gets the value we set # Or if we omit the first one... $object->methodname() # Actually calls the method
So, my questions are : thanks

In reply to Memoizing Methods by bduggan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.