当我查询数据库并在mysqli_result中检索结果时,内存使用量极小.但是,当我将查询结果中的所有行提取到关联数组中时,内存使用率变得非常高.
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
?>
对我来说,存储这么多结果非常消耗内存是有道理的,但我只是想知道 mysqli_result 怎么这么小.不可能是每次调用fetch_assoc的时候都向dbase查询结果.那么结果存储在内存中的什么地方.
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.
获取结果和存储指向资源的指针之间存在巨大差异.
There is a HUGE difference between fetching results and storing a pointer to a resource.
如果你在第一次调用 memory_get_usage();
之前 echo $r;
,你会意识到它只是一个指针.这是指向结果集的指针.在您获取
结果之前,结果集实际上不会存储到内存中.
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()
来执行您要执行的操作.这将导致 1 个方法以更好的性能访问您的所有结果,因为它是在 mysqli 扩展(C 库)而不是 PHP 中的循环上典当的.
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.
您还可以使用免费结果功能在完成后从内存中清除结果.如果您熟悉,这就像在 Java 中关闭游标一样.
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.
这篇关于PHP:查询结果如何存储在 mysqli_result 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!