在大数据库中加入查询需要大量的查询时间。创建一个巨型数组不会是解决方案,因为声明巨型数组并且每次运行只使用少数条目是多余的。
你在找什么是memcache。 Memcache在服务器的RAM上像一个数组一样工作。 Php不会每次声明数组并缓存它。相反,memcache将数据保存在RAM中即可使用。你可以在memcache中设计你的基于id的定义并使用它。
我的建议是宣布一个对象扩展数组类。如果数据在缓存中,您可以重载构造函数以检索数据。如果不是,它应该从数据库中获取数据并添加到memcache中。
只要您定义,数据就会在缓存中。
尽量不要制造巨大的阵列。
http://php.net/manual/en/book.memcache.php
这是我一直在使用的类。如果你有一些由常量数据组成的表,我建议你使用带有88000秒时间限制的cacheTable方法,并且每天添加一个cronjob来重新缓存它。
<?php
class mc extends ArrayObject{
var $mc_obj;
function __construct(){
$this->mc_obj = new Memcache;
$this->mc_obj->connect("127.0.0.1",11211);
# You might need to set "127.0.0.1" to "localhost"
}
function fetch($table,$id){
/*
if the n-th row of the $table is not in the cache, cache it
return the row.
*/
if(!$this->mc_obj->get($table."_".$id)){
$this->cacheById($table,$id);
}
return $this->mc_obj->get($table."_".$id);
}
/*
numeric is the boolean for mysql_fetch type.
if true the the array will be created numeric with mysql_fetch_row
else the array will be created associative with mysql_fetch_assoc
*/
function cacheTable($table,$numeric=false,$conditions="1",$idFieldOfTable="id",$cacheTimeLimit=120){
$q1 = mysql_query("select * from `".$table."` where ".$conditions.";");
if($numeric){
while($row = mysql_fetch_row($q1)){
$this->mc_obj->set($table."_".$row[0],$row,false,$cacheTimeLimit);
}
}
else{
while($row = mysql_fetch_assoc($q1)){
$this->mc_obj->set($table."_".$row[$idFieldOfTable],$row,false,$cacheTimeLimit);
}
}
}
function cacheById($table,$id,$numeric=false,$idFieldOfTable="id",$cacheTimeLimit=120){
$q1 = mysql_query("select * from `".$table."` where `".$idFieldOfTable."`=".$id." Limit 1;");
if($numeric){
$row = mysql_fetch_row($q1);
}
else{
$row = mysql_fetch_assoc($q1);
}
$this->mc_obj->set($table."_".$id,$row,false,$cacheTimeLimit);
}
public function offsetGet($key) {
$id = substr($key,strrpos($key,"_")+1);
$table = substr($key,0,strrpos($key,"_"));
return $this->fetch($table,$id);
/*
By overriding this method you will be able to call any particular cell like
$cell = $memCacheObject['tableName_Rowid']['field'];
*/
}
}
?>
下面是如何使用:
<?php
mysql_connect("localhost","root","");
mysql_select_db("DB_NAME");
$db = new mc();
$table = "city";
$id = 3;
$a = $db->fetch($table,$id);
// $a is the associative row array
$b = $db->fetch($table,$id);
// $b is the numeric row array
$cell = $db['city_18']['name'];
//$cell is the name of the city with id 18 in the city table
//in order to cache the whole table
$db->cacheTable("city",false,"1","id",90000);
?>
“我真的改善这种代码在性能方面?”您需要自己测试一下 - 在您的更改前后使用实际工作负载对性能进行基准测试。 – 2011-01-13 13:43:50