This tutorial will explain many small techniques which will, hopefully, help optimize your php scripts. I considered myself a bit of a PHP pro until I started researching some of this stuff and realized that there is a whole realm of information out there about optimizing php that I didn’t know about. I hope you will be as surprised as I was about some of the things you might learn from this article.
When outputting strings:
Output of Data
So first off lets start with outputting data to the user. Here are some handy tips to remeber:When outputting strings:
Single quotes (’) with concatenation is faster than putting your variables inside a double quote (”) string. (cite)
echo 'a string ' . $name; //is faster than echo "a string $name";
Use echo’s multiple parameters instead of string concatenation. (cite)
echo 'this', 'is', 'a', $variable, 'string'; //is faster than echo 'this' . 'is' . 'a' . $variable . 'string';
Loops and Counting
Here are some ways to make your loops and counting a bit more efficient.
Use pre-calculations and set the maximum value for your for-loops before and not in the loop. This means you are not calling the count() function on every loop. (cite)
$max = count($array); for ($i = 0; $i < $max; $i++) //is faster than for ($i = 0; $i < count($array); $i++)
Use isset where possible in replace of strlen. (cite)
if (!isset($foo{5})) { echo "Foo is too short"; } //is faster than if (strlen($foo) < 5) { echo "Foo is too short"; }
Use pre-incrementing where possible as it is 10% faster. (cite)
++$i; //is faster than $i++;
- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. (cite)
Variables and Functions
There are some handy things you can do with variables and functions in php to help optimize your script.
Unset or null your variables to free memory, especially large arrays. (cite)
Use require() instead of require_once() where possible. (cite)
Use absolute paths in includes and requires. It means less time is spent on resolving the OS paths. (cite)
include('/var/www/html/your_app/test.php'); //is faster than include('test.php');
require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference. (cite)
“else if” statements are faster than “switch/case” statements. (cite)
No comments:
Post a Comment