面对一个问题,我在使用数据库时找不到内存泄漏。该脚本从数据库中获取大量数据,因此内存泄漏至关重要。使用 mysqli、mysql 或 PDO 时会出现此问题。这是测试代码:
$link = mysqli_connect('localhost', 'root', '');
if (!$link) {
die('Connection error: ' . mysql_error());
}
mysqli_select_db($link, 'coolstat.my') or die ('Can\'t use coolstat.my: ' . mysql_error());
for($ii=0; $ii<20000; $ii+=1000){
$sql= "SELECT `codes_data`.* FROM `codes_data` INNER JOIN codes ON codes.siteid= 20 AND codes.codeid=codes_data.codeid LIMIT ".$ii.", ".($ii+1000)."";
///
$data= array();
$result = mysqli_query($link, $sql);
while (($row = mysqli_fetch_array($result))){
$data[]= $row;
}
mysqli_free_result($result);
unset($result);
unset($data);
echo "Memory get_data usage: ".convert_memory_val(memory_get_peak_usage(true))."<br />\n";
}
mysqli_close($link);
function convert_memory_val($size){
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}
它输出:
Memory get_data usage: 3.25 mb
Memory get_data usage: 6 mb
Memory get_data usage: 9 mb
Memory get_data usage: 11.75 mb
Memory get_data usage: 14.75 mb
Memory get_data usage: 17.75 mb
Memory get_data usage: 20.5 mb
Memory get_data usage: 23.5 mb
Memory get_data usage: 26.5 mb
Memory get_data usage: 29.5 mb
Memory get_data usage: 32.25 mb
Memory get_data usage: 35.25 mb
Memory get_data usage: 38.25 mb
Memory get_data usage: 41.25 mb
Memory get_data usage: 44 mb
Memory get_data usage: 47 mb
Memory get_data usage: 50 mb
Memory get_data usage: 53 mb
Memory get_data usage: 56 mb
Memory get_data usage: 58.75 mb