問題描述
當(dāng)我查詢數(shù)據(jù)庫并在mysqli_result中檢索結(jié)果時,內(nèi)存使用量極小.但是,當(dāng)我將查詢結(jié)果中的所有行提取到關(guān)聯(lián)數(shù)組中時,內(nèi)存使用率變得非常高.
When I made a query to the database and retrieve the results in mysqli_result, the memory usage is extremely small. However, when I fetch all the rows in the query results in to an associative array, the memory usage becomes extremely high.
<?php
require_once("../config.php"); //db connection config
$db = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DBASE);
$query ="select * from table_name";
if($r = $db->query($query)){
echo "MEMORY USAGE before : ". memory_get_usage()."<br><br>";
$rows = array();
while($row = $r->fetch_assoc()){
$rows[]= $row;
}
echo "MEMORY USAGE after : ". memory_get_usage()."<br><br>";
//before: 660880
//after: 114655768
// # of records: around 30 thousands
?>
對我來說,存儲這么多結(jié)果非常消耗內(nèi)存是有道理的,但我只是想知道 mysqli_result 怎么這么小.不可能是每次調(diào)用fetch_assoc的時候都向dbase查詢結(jié)果.那么結(jié)果存儲在內(nèi)存中的什么地方.
It makes sense to me that storing this many results is very memory consuming, but I'm just wondering how come mysqli_result is so small. It can't be that the results are queried to the dbase every time fetch_assoc is called. So then where are the results stored in the memory.
推薦答案
獲取結(jié)果和存儲指向資源的指針之間存在巨大差異.
There is a HUGE difference between fetching results and storing a pointer to a resource.
如果你在第一次調(diào)用 memory_get_usage();
之前 echo $r;
,你會意識到它只是一個指針.這是指向結(jié)果集的指針.在您獲取
結(jié)果之前,結(jié)果集實際上不會存儲到內(nèi)存中.
If you echo $r;
before your first call to memory_get_usage();
, you will realize it is just a pointer. This is the pointer to your result set. Until you fetch
your results, the result set will not actually be stored into memory.
我建議您運行 fetchAll()
來執(zhí)行您要執(zhí)行的操作.這將導(dǎo)致 1 個方法以更好的性能訪問您的所有結(jié)果,因為它是在 mysqli 擴展(C 庫)而不是 PHP 中的循環(huán)上典當(dāng)?shù)?
I would suggest that you run fetchAll()
for what you are trying to do. This will then result in 1 method accessing all your results with better performance since it's pawned off on the mysqli extension (C Library) rather than a loop in PHP.
您還可以使用免費結(jié)果功能在完成后從內(nèi)存中清除結(jié)果.如果您熟悉,這就像在 Java 中關(guān)閉游標一樣.
You can also use the free results function to clear your results from memory when you are done with them. This is like closing a cursor in Java if you are familiar.
這篇關(guān)于PHP:查詢結(jié)果如何存儲在 mysqli_result 中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!