简单的数据缓存技术[转一] o^<W3Z
uN(N2m
简单的数据缓存技术 PF:E{_~
I7jIA>ZZi
近来做了一阵子程序性能的优化工作,有个比较有意思的想法,想提出来和大家交流一下。 'jBtBFzP-
Cache是“以空间换时间”策略的典型应用模式,是提高系统性能的一种重要方法。缓存的使用在大访问量的情况下能够极大的减少对数据库操作的次数,明显降低系统负荷提高系统性能。相比页面的缓存,结果集是一种“原始数据”不包含格式信息,数据量相对较小,而且可以再进行格式化,所以显得相当灵活。由于PHP是“一边编译一边执行”的脚本语言,某种程度上也提供了一种相当方便的结果集缓存使用方法——通过动态include相应的数据定义代码段的方式使用缓存。如果在“RamDisk”上建缓存的话,效率应该还可以得到进一步的提升。以下是一小段示例代码,供参考。 Sigu p#.p
.jRv8x b
<? *+<H4.W
H
// load data with cache :c0 |w
function load_data($id,$cache_lifetime) { Kg#s<# h
:w:ql/?X
// the return data [3io6XG x@
$data = array(); a}7P:e*u
r8[Ywn<u
// make cache filename eHH9#Vrhc$
$cache_filename = ‘cache_‘.$id.‘.php‘; gOm%?sg
\`WAG>'l5
// check cache file‘s last modify time n|!O .+\b
$cache_filetime = filemtime($cache_filename); No(S#,vJ;
5
OF*PBZ
if (time() - $cache_filetime <= $cache_lifetime) { q??N,
//** the cache is not expire
Ox+}JB
[
include($cache_filename); R!7a;J}
} else { scR+F'M
//** the cache is expired ]`eJSk.
??XtN.]7
// load data from database wm/>_
// ... K${CHKFf
while ($dbo->nextRecord()) { u
%&4[zb
// $data[] = ... ~,reS:9RZ
} {aWfD XB1
~Ec@hz]js
// format the data as a php file tq5o
$data_cache = "<?\r\n"; Aq{7WA
while (list($key, $val) = each($data)) { a: [m;
$data_cache .= "\$data[‘$key‘]=array(‘"; ceNJXK
$data_cache .= "‘NAME‘=>\"".qoute($val[‘NAME‘])."\"," `/eh
$data_cache .= "‘VALUE‘=>\"".qoute($val[‘VALUE‘])."\"" LZrkFkiC
$data_cache .= ");\r\n"; (JeRJ4
} _ +A$6l
$data_cache = "?>\r\n"; K@;ls
iuWw(dJk
// save the data to the cache file
<