在大數據庫中加入查詢需要大量的查詢時間。創建一個巨型數組不會是解決方案,因爲聲明巨型數組並且每次運行只使用少數條目是多餘的。
你在找什麼是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