Memory management
Quite often, PHP developers need to deal with a large amount of data. While large is a relative term, memory is not. Certain combinations of functions and language constructs, when used irresponsibly, can clog our server memory in a matter of seconds.
Probably the most notorious function is file_get_contents()
. This easy-to-use function literally grabs the content of an entire file and puts it into memory. To better understand the issue, let's take a look at the following example:
<?php $content = file_get_contents('users.csv'); $lines = explode("\r\n", $content); foreach ($lines as $line) { $user = str_getcsv($line); // Do something with data from $user... }
While this code is perfectly valid and working, it is a potential performance bottleneck. The $content
variable will pull the content of the entire users.csv
file into memory. While this could work for a small file size, of let's say a couple of megabytes, the code is not performance optimized. The moment users...