Memoize or the other techniques shown in HOP should work, the thing to remember is that you really can only cache "value objects" which are immutable. And if the instances aren't intrinsically immutable you want to be very careful to use whatever clone method or copy constructor is provided before you do make changes to them.
As an example we use a wrapper class at $work around DateTime instances, and I often wind up writing a caching sub to call the wrapper class' convenience constructor for "mm/dd/yyyy" dates:
{
my %_mdy_cache;
sub _from_mdy {
my $mdy = shift;
return $_mdy_cache{ $mdy } ||= Our::DateTime->from_mdy( $mdy, "/"
+);
}
}
But you've then got to be very careful to call $dt_instance->clone() before changing the instances because otherwise you wind up altering the cached instances and the next person to ask for "m/d/y" gets "m/d+2/y" because you didn't before you called $foo->add( days => 2 ).
The cake is a lie.
The cake is a lie.
The cake is a lie.
|