[英]PHP Exception memory leak
在我的控制台應用程序中,我將顯示所有PHP內置錯誤類型的顯示替換為拋出ErrorException
:
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting
return;
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
它很好用,但是有一個問題。 考慮以下代碼段:
for ($id = 1;; $id += 1) {
try {
$html = file_get_contents('https://stackoverflow.com/boo/' . $id);
} catch (Exception $exception) {
// Failed
}
}
拋出的每個ErrorException
保留堆棧歷史記錄。 在實際示例中,缺少某些ID,這會導致這種情況,因此在進行數千次迭代之后,最終會發生內存泄漏。
如何解決此問題? 拋出和捕獲異常是循環錯誤嗎? 還是我可以以某種方式禁用堆疊行為?
一旦在每次迭代中使用了Exception對象,就可以取消設置它:
function getLevels($start_idx,$levels = 9){
try {
return $this->getBinaryTree($levels);
} catch (Exception $e) {
switch($e->getMessage()){
case "Almost out of memory":
$max_tree_depth = (int)($levels/2);
if($max_tree_depth >= 2){
unset($e); // <------------------------ RIGHT HERE!
return $this->getLevels($start_idx,$max_tree_depth);
}else{
throw new Exception("Out of memory even after getting tree with 2 levels");
}
break;
default:
throw $e;
}
}
}
我在下面的鏈接上找到了解決方案:
https://stuporglue.org/php-memory-leak-when-throwing-catching-and-recursing/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.