Two two liner performance boosters for web apps

Hear ye, hear ye, hark to the lazy masters’ cabin and partake of the wisdom of a traditional KISS .

I was writing a  CGI application in PERL for a project, yes I am indeed that old a hand, and I took a few optimization steps. First I installed mod_cgi and the perl fastcgi libs. Furthermore to exploit data locality in subsequent invocations of the scripts I hand crafted a hash based cache scheme.

While debugging the application I noticed that my  hand crafted cache was not being updated. After sleeping on it I realized that mod_cgi rotates each call to the script to a different instantiation of it in the pool it creates. What this effectively means is that I had as many hash based caches as the number of processes mod_cgi was spawning with no data locality between the different instances.

So OK I thought I need a shared memory segment and a way for my hash to reside on that segment. So after a bit of CPAN searching I got sharelite thus:

# shared memory segment for the global cache
use Tie::ShareLite qw( :lock );
my $ipc = tie my %CACHE,
‘Tie::ShareLite’, -key     => 2010,
-mode    => 0600,
-create  => ‘yes’,
-destroy => ‘yes’
or die(“Could not tie to shared memory: $!”);

But wait, since sharelite did all this work, I wondered  is there another module that can do all my intelligent caching work ? Here is another two liner that can save copious amounts of work,

use Memoize;

memoize(“DoDNS”,    SCALAR_CACHE => [HASH => %CACHE]);

So what I have now is a persistent shared memory cache of the invocations of the DoDNS function that is resilient even on application termination. And if you are concerned of hash initialization here is the final one liner.

delete @CACHE{keys %CACHE};

Done  in a very KISSable fashion.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: