Hello,
Say I want to create a package with this framework:
package my_test_package;
# Create a package global.
my $ME = undef;
# Return the required reference.
sub new {
# If $ME has been set do not bother doing all the init again.
return $ME if defined $ME;
my $class = shift;
my $self = {};
# A lot of long-winded initialization.
bless $self, $class;
$ME = $self;
return $self;
}
1;
The basic idea is to avoid running through all the longwinded setting up several times. This is intended to be run under something such as mod_perl where the object might actually hang around for weeks, leading to performance gains.
My question is 'Is this a good idea?' I can think of the following pros and cons:
- Pro:
- Creating a new instance of an object is much faster as it needs only return a reference if the init code has been run once already.
- Con:
- It could prove dangerous if the module is internally altered during use, the same object could be in scope in several places. This shortcut is only usable for unchanging modules (such as allowing object orientated access to fixed configuration values).
- Con:
- There could be a serious memory penalty if the code is sloppy as it could be possible for garbage collection to never run. Also packages loaded from our package will also persist.
- Pro:
- Values can persist in the package between different objects. For example if it was a module for keeping track of high scores then a new score object could be created which would have in it all the previous scores for this process. (This "feature" could rapidly become a bug)
I suppose I really want your opinions on wether the risks involved outweigh the benefits. Are there any safeguards that could be put in place to keep the code safer? Any thoughts would be much appreciated.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.