This Will Optimizing Your PHP Code and Change Your Coder Mind
When you want to optimize your script, you first check your database and try to optimize your algorithms. There aren't many pure PHP performance tips that are going to matter.
Let's see :
- Concatening variables is faster than just putting them in a double-quotation mark string.
$var = 'Hello ' . $world; // is faster than $var = "Hello $world"; // or $var = "Hello {$world}";Yes, it's faster, but the second and third form are even more readable and the loss of speed is so low it doesn't even matter. - When using a loop, if your condition uses a constant, put it before the loop. For instance :
for ($i = 0; $i < count($my_array); $i++)
This will evaluate count($my_array) every time. Just make an extra variable before the loop, or even inside :for ($i = 0, $count = count($my_array); $i <$count; $i++) - The worst thing is definitely queries inside loops. Either because of lack of knowledge (trying to simulate a JOIN in PHP) or just because you don't think about it (many insert into in a loop for instance).
$query = mysql_query("SELECT id FROM your_table"); while ($row = mysql_fetch_assoc($query)) { $query2 = mysql_query("SELECT * FROM your_other_table WHERE id = {$row['id']}"); // etc
Never do this. That's a simple INNER JOIN.