首页 > 开发 > PHP > 正文

如何提高PHP速度第1/3页

2024-05-04 22:13:45
字体:
来源:转载
供稿:网友
简单的数据缓存技术 

  近来做了一阵子程序性能的优化工作,有个比较有意思的想法,想提出来和大家交流一下。 
  Cache是“以空间换时间”策略的典型应用模式,是提高系统性能的一种重要方法。缓存的使用在大访问量的情况下能够极大的减少对数据库操作的次数,明显降低系统负荷提高系统性能。相比页面的缓存,结果集是一种“原始数据”不包含格式信息,数据量相对较小,而且可以再进行格式化,所以显得相当灵活。由于PHP是“一边编译一边执行”的脚本语言,某种程度上也提供了一种相当方便的结果集缓存使用方法——通过动态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 = "<?/r/n"; 
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 .= ");/r/n"; 

$data_cache = "?>/r/n"; 

// save the data to the cache file 
if ($fd = fopen($cache_filename,‘w+‘)) { 
fputs($fd,$data_cache); 
fclose($fd); 


return $data; 

?> 

适用情况: 
1.数据相对比较稳定,主要是读取操作。 
2.文件操作要比数据库操作快。 
3.复杂数据访问,大数据量访问,密集数据访问,系统数据库负载极重。 
4.Web/DB分离结构或者多Web单DB结构。 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表