PHP is not known to be a demon of speed and it can sometimes happen that programmers do not account for how successful a web application can quickly become.
Things that work "fine" when 300 users are topping the groups in a database can make the whole application literally unresponsive when there is a need to import 3000 users into a single group.
It is not even that big of a number in terms of user count, but it is a big number when you consider that there can be 3000 select queries in your application that can themselves make more queries for related data.
Below are 7 things that can help you with performance problems of your PHP applications.
$file = file_get_contents($filename);PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 266240 bytes)By looping and parsing file partially, line by line, gathering all the necessary data before preserving it in the database, you will use much less memory at once.$file = new SplFileObject($filename); // SplFileObject is a PHP internal class to deal with files.
// Loop line by line processing data from the file
while (!$file->eof()) {
// $line will be overriden on each loop iteration
$line = $file->fgets();
// Process the line further, if you need more than one line you can add it to array before you process it.
}
// This loop will make a select query for every user.
// $users is an array of integer identifiers for simplicity.
foreach ($users as $userId) {
// Always use prepared statements for speed and security!
$result = DB::raw('SELECT * FROM articles WHERE user_id = ?', $userId);
// Process record further
}
// Below example will query database once before the loop and just process the records pulled.
$placeholders = array_fill(0, count($users), '?');
$results = DB::raw("SELECT * FROM articles WHERE user_id IN $placeholders", $users);
foreach ($results as $result) {
// Process record further
}
// Pull the first page
SELECT * FROM users ORDER BY name ASC LIMIT 100 SKIP 0
// Pull the second page when browser requests it
SELECT * FROM users ORDER BY name ASC LIMIT 100 SKIP 100
// Count will be processed every loop iteration
for ($i = 0; $i < count($array); $i++) {
echo $array[$i];
}
foreach ($array as $key => $record) {
echo $record;
}
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$n = ;
}
echo (microtime(true) - $start) . ' seconds';
0.10738110542297 seconds
$i = 0;
// We measure current amount of RAM used by this PHP process
echo memory_get_usage();
echo PHP_EOL; // New line for convenience
// We add more stuff
$s = [1, 2, 3, 4, 5];
// We check memory usage again and compare for difference
echo memory_get_usage();
10864408
10864440
How logging can simplify complex problems
23 guidelines for writing readable code
Event-driven programming
Bitmask - why, how and when
Entity Component System