Practical mod_perl / HTML Book /



previous page: 13.10. Caching and Pre-Caching
  
page up: HTML Version of the book
  
next page: 13.12. Comparing Runtime Performance of Perl and C

13.11. Caching with Memoize


If you have a subroutine with simpler logic, where a returned value is solely a function of an input, you can use the Memoize module, which does the caching automatically for you. The gist of its usage is giving the name of the function to be memoize( ) d:

use Memoize;
memoize('slow_function');
slow_function(arguments);

Remember that in our case we had two caches: one for the text versions of the calendars and the other for HTML components. The get_text_calendar( ) function is responsible for populating the text calendar's cache. It depends only on inputs, so we could rewrite it as:

use Memoize;
memoize('get_text_calendar');
sub get_text_calendar {
    my($year,$month) = @_;
    warn "$year,$month\n" if DEBUG;
    my $cal = Date::Calc::Calendar($year, $month);
    chomp $cal;
    return $cal;
}

We have added another debug warning to check that the cache is actually working. If you want to test it under mod_perl, set DEBUG to a true value, start the server in single-process mode (-X), and issue requests to the calendar registry script we just discussed.

You can also control the size of the cache and do other automatic cache manipulations with Memoize. See its manpage for more information.

The get_html_calendar( )subroutine cannot be memoize( ) d because the returned value depends on the relation between the requested date and the current date, in addition to the normal input/output relation.

 

Continue to:

  • prev: 13.10. Caching and Pre-Caching
  • Table of Contents
  • next: 13.12. Comparing Runtime Performance of Perl and C







TOP
previous page: 13.10. Caching and Pre-Caching
  
page up: HTML Version of the book
  
next page: 13.12. Comparing Runtime Performance of Perl and C


Menu

  • HTML Book
  • PDF Book
  • Download Code
  • Table of Contents
  • Errata
  • mod_perl2 User's Guide
  • Sitemap

Search


Add to Google




Creative Commons License


Written by
Eric Cholet (Logilune) and
Stas Bekman (StasoSphere & Free Books).


[ Privacy Policy | Terms of Use | About Us | Search ]

© 2007 StasoSphere.com