Mutant has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I've got a mod_perl handler that, based on the Location of the request, loads a sub-class, and calls methods off that class rather than the base class to do all it's processing, ie something like this:

my $class = 'Class::Base'; if ($has_sub_class) { $class = 'Class::' . $sub_class_name; eval("require $class"); } my $object = $class->new; $object->do_stuff;

I've done it this way because there will potentially be hundreds of different sub-classes, so I don't want to load them all every time.

My question is two-fold. Firstly, is this a sane way to do it?

And secondly, what effects will this have? ie, Even though the class will be loaded on demand, I'm guessing the memory won't then be freed from the Apache process once the request has been made. Will this have an effect on performance other than just memory usage? Any ideas on tweaking Apache to minimise this?

Thanks.

Replies are listed 'Best First'.
Re: Run time require's and mod_perl
by ides (Deacon) on Nov 22, 2004 at 17:10 UTC

    If you preload all of your classes in your httpd.conf or startup.pl the memory used will be shared amongst the Apache children.

    I would suggest checking out this link mod_perl: Performance Tuning

    Frank Wiles <frank@wiles.org>
    http://www.wiles.org

Re: Run time require's and mod_perl
by perrin (Chancellor) on Nov 22, 2004 at 17:10 UTC
    In general the preferred way to handle loading in any persistent environment like mod_perl is to load all modules up front before forking to maximize sharing via copy-on-write. If you have a situation where many classes may never get used during the lifetime of an apache child process, loading on demand may be better. It really depends on how likely you are to use these classes in any given child process and how much they increase your memory useage. See the mod_perl docs for more discussion on this topic.
Re: Run time require's and mod_perl
by ikegami (Patriarch) on Nov 22, 2004 at 17:11 UTC

    If $sub_class_name comes in part or in whole from the user, be sure to validate it.

    You should check if eval succeeds. It conveniently returns true or false in this case, so you can use the return value or $@ to check for errors.

    You could also get rid of eval "" to speed things up (and decrease the chance of a security problem):

    $class = "Class/${sub_class_name}.pm"; eval { require $class } or die("Error loading sub-class: $@$/");