Created
July 10, 2016 17:22
-
-
Save amcsi/5c43dc40bf5ec38fe7f560c1973194ec to your computer and use it in GitHub Desktop.
PHP memory leak
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function printMemoryUsage() { | |
| gc_collect_cycles(); | |
| printf("Memory used: %.4fMB\n", memory_get_usage() / 1024 / 1024); | |
| } | |
| gc_enable(); | |
| $batchCount = 1000; | |
| $iterations = 10000; | |
| class Container { | |
| private $data; | |
| public function __construct(array $data) | |
| { | |
| $this->data = $data; | |
| } | |
| public function getData() | |
| { | |
| $data = $this->data; | |
| // trigger copy-on-write again. | |
| $data[2] = 'write'; | |
| return $data; | |
| } | |
| } | |
| $data = range(0, 10); | |
| $output = []; | |
| printMemoryUsage(); | |
| echo "--Doing array usage..."; | |
| printMemoryUsage(); | |
| /** | |
| * Iterating using only arrays | |
| */ | |
| for ($i = 0; $i < $iterations; $i++) { | |
| $item = $data; | |
| // trigger copy-on-write | |
| $item[1] = 'write'; | |
| $output[] = $item; | |
| if ($i && !($i % $batchCount)) { | |
| printMemoryUsage(); | |
| } | |
| } | |
| $output = []; | |
| $item = null; | |
| echo "--Reset after array usage\n"; | |
| printMemoryUsage(); | |
| /** | |
| * Iterating using objects | |
| */ | |
| for ($i = 0; $i < $iterations; $i++) { | |
| $item = $data; | |
| // trigger copy-on-write | |
| $item[1] = 'write'; | |
| $instance = new Container($item); | |
| $output[] = $instance->getData(); | |
| if ($i && !($i % $batchCount)) { | |
| $instance = null; | |
| printMemoryUsage(); | |
| } | |
| } | |
| $output = []; | |
| $item = null; | |
| $instance = null; | |
| echo "--Reset after object usage\n"; | |
| printMemoryUsage(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment