Thursday, April 28, 2005

Cache_Lite is your best friend. Ever.

One of those things you always mean to do once you get your code working is to make it faster.

Cache_Lite does it. But not only where you think. My typical plan of action is to:
  • Idea - Connect to remote machine.
  • Implementation - Use HTTP_Request to acquire the content into a string, then parse it with XML_Serializer. Rip out the bits you need into an array, and move on.
  • Test - Machine opens http connections, fetches, parses, spits out an actual result compared to whatever it is you expected. Start to finish: 15 seconds. Multiple web services? Forget it!
  • Refactor - Fix a bug and retest.
With optimize somewhere off in the misty distance. The idea of unit testing is to have known input before hand - but it's often effort to reach ahead and grab the actual response XML string, and put that into the code, as well as comment things out.
It's finicky, infact.

Putting my money where my mouth is:
require_once 'FilmTrust.php';
require_once "Services/Upcoming.php";
require_once "Cache/Lite.php";

$options = array(
'cacheDir' => 'cache/',
'automaticSerialization' => true,
'lifeTime' => 7200,
'pearErrorMode' => CACHE_LITE_ERROR_DIE
);

$cache = new Cache_Lite($options);

$eventClient = new Services_Upcoming();
$eventClient->setApi("ae75bbe10a");

if ($events = $cache->get('events')) { }
else {
$events = $eventClient->watchlist_getList('CloCkWeRX','password');
$cache->save($events, 'events');
}


for ($i=0; $i<count($events); $i++) {
if ($event = $cache->get('event.' . $events[$i]["event_id"])) { }
else {
$event = $eventClient->event_getInfo($events[$i]["event_id"], "CloCkWeRX", "password");
$cache->save($event, 'event.' . $events[$i]["event_id"]);
}
}
print_r($events);
print_r($event);

Above, we see something beautiful. Caching speeds up the testing cycle more than a hundred fold. I'd say that my poor laptop would take up to 15 seconds from start to finish before. Now, it takes 15 seconds the first time, and about half a second every subsequent time.

It rocks. If something goes wrong, it's an easy matter to delete the entire cache and reload the page.

So, the new mantra:
  • Idea
  • Implement Caching
  • Implement Everything Else
  • Test
  • Refactor
Too easy!

No comments: