Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is all memory released when php request ends?

In php is all the memory allocated to run my script released at the end of my page request or do I need to worry about memory leaks building up over time?

like image 464
Toby Allen Avatar asked Jan 21 '13 08:01

Toby Allen


3 Answers

No. You do not need to manually free (call unset()) resources. PHP will do this automatically. Everything gets free'd at the end of the request lifetime. So no, you do not need to bother with this. If you do this:

<?php
$resource = allocate_heavy_resource();
?>

The $resource will get freed at the end of the request and so this will not leak memory. If it does than that means there is a serious bug in PHP and any discussion of normal operation goes through the window anyway.

EDIT: There are exceptions, of course. Like persistent database connections. But those get handled eventually, so its not really a memory leak.

like image 66
mishmash Avatar answered Sep 21 '22 18:09

mishmash


PHP does release memory that you claim by building objects etc. Still there are scenarios where memory is NOT released. For this the principle of garbage collection was introduced in version 5.3.

You can use the gc_enable() function to execute it. Garbage collection in PHP is NOT active by default.

like image 41
user1914292 Avatar answered Sep 21 '22 18:09

user1914292


Kind of, Memory leaks occur when things are cached. So if you have memory leaks in your php script your apache processes will increase over time, You can restart them after so many requests. Check the your Multi Processing Module (MPM) usually prefork or worker.

Most cases though this wont effect you much unless your doing a lot of processing with PHP

like image 40
exussum Avatar answered Sep 23 '22 18:09

exussum