A Quick Lesson in Memcached
Someone posted on the devshed boards recently regarding memcached:
“I can’t fully grasp the idea of how i could use this to perform faster queries.”
It’s actually quite simple - it’s faster to retrieve something out of memory that out of a database. You just need a unique identifier for that item.
function run_test() {
$memcache = new Memcache;
$memcache->connect(’localhost’, 11211) or die (”Could not connect”);//see if the result already exists in memcache
$data = $memcache->get(’tests’);if (!$data) {
$data = array();
//the result was not found, we have to run the query
$result = mysql_query(”select test,test1 from tests”);if (!$result) {
//error doing the query
return false;
} else {
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}//now we’ve got the data stored in an array $data, save it to memcache
$memcache->set(”tests”, $data, false, 60); //save it for 60 seconds, uncompressed
}
}//return the array
return $data;
}
This does make the assumption that this is the only place the key “tests” is saved to memcache. The key must be unique for each query you want to run like this.
As a side note, the code highlighters I installed for wordpress really sucks.