浅谈
PHP 缓存技术之一
近来做了一阵子程序性能的优化工作,有个比较有意思的想法,想提出来和大家交流一下。
Cache 是“以空间换时间”策略的典型应用模式,是提高系统性能的一种重要方法。缓存的使
用在大访问量的情况下能够极大的减少对
操作的次
数,明显降低系统负荷提高系统
性能。相比页面的缓存,结果集是一种
“原始数据”不包含格式信息,数据量相对较小,而且
可以再进行格式化,所以显得相当灵
活。由于
“一边编译一边执行”的脚本语言,某种
程度上也提供了一种相当方便的结果集缓存使用方法
——通过动态 include 相应的数据定义
代码段
的方式使用缓存。如果在“RamDisk”上建缓存的话,效率应该还可以得到进一步的提
升。以下是一小段示例代码,供参考。
// load data with cache
function load_data($id,$cache_lifetime) {
// the return data
$data = array();
// make cache filename
$cache_filename = ‘cache_‘.$id.‘.php‘;
// check cache file‘s last modify time
$cache_filetime = filemtime($cache_filename);
if (time() - $cache_filetime <= $cache_lifetime) {
//** the cache is not expire
include($cache_filename);
} else {
//** the cache is expired
// load data from database
// ...
while ($dbo->nextRecord()) {
// $data[] = ...
}
// format the data as a php file
$data_cache = "
while (list($key, $val) = each($data)) {
$data_cache .= "$data[‘$key‘]=array(‘";
$data_cache .= "‘NAME‘=>"".qoute($val[‘NAME‘])."","
$data_cache .= "‘VALUE‘=>"".qoute($val[‘VALUE‘])."""
$data_cache .= ";);rn";
}
$data_cache = "?>rn";
// save the data to the cache file
if ($fd = fopen($cache_filename,‘w+‘)) {
fputs($fd,$data_cache);
fclose($fd);
}
}
return $data;