PHP Optimization Tips
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.
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";
Or even better:
-
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++)
When checking the length of strings:
-
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"; }
When incrementing:
-
Use pre-incrementing where possible as it is 10% faster. (cite)
++$i; //is faster than $i++;
And
- 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)
Other Tips
These tips aren’t so much for speed optimization, rather they are good practices.
-
Error suppression with @ is very slow. (cite)
if (isset($albus)) $albert = $albus; else $albert = NULL; //is faster than $albert = @$albus;
-
Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags. (cite)
-
Never trust variables coming from users (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML (cite)
//a safe query $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", mysql_real_escape_string($user), mysql_real_escape_string($password)); //safe output echo htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); //output: <a href='test'>Test</a>
-
Avoid using plain text when storing and evaluating passwords. Instead use a hash, such as an md5 hash. (cite)
$user_input = 'myPassword'; if (md5($user_input) == $md5_password_from_database) { //login here... }
-
Use ip2long() and long2ip() to store IP addresses as integers instead of strings. (cite)
Conclusion
So there you have it. Some handy tips to help optimize your php scripts. For further reading why not check out these articles:
- 50+ PHP optimisation tips revisited
- 40 Tips for optimizing your php code
- A HOWTO on Optimizing PHP
- 10 things you (probably) didn’t know about PHP










if (!isset($foo[5])) { echo “Foo is too short”; }
Should be used instead of the following, due to depreciation
if (!isset($foo{5})) { echo “Foo is too short”; }
This is a great help to me, thank you
PHP Optimization Tips | ProgTuts…
This tutorial will explain many small techniques which will, hopefully, help optimize your php scripts….
STUMBLED!
Useful tips, will need to look at how to implement some of these tips into my current script.
Submitted this tutorial to:
http://www.newsdots.com/tutorials/php-optimization-tips-progtuts/
I am very sorry to say that:
You won’t gain anything SIGNIFICANT by using any of these. Believe me or not, gaining 0.5 second per request won’t be noticed by anybody.
Of course, if you start a script from scratch, it is a good habbit to follow good practices but don’t even bother looking at optimizing anything using these tips.
Among the good practices, I would, instead of you, advice to always embrace your conditional blocks.
if($condition)
$a = $b++;
else
$a = 0;
will break when inserting debug code, for instance
if($condition)
$a = $b++;
echo ‘a is ‘.$a;
else
$a = 0;
prefer
if($condition){
$a = $b++;
}
else{
$a = 0;
}
or, better:
$a = $condition ? $b++ : 0;
Regarding optimization, here are the things which DO work:
1- use cache as often as you can.
Cache your outputs. If you are using a business layer, cache your objects.
Memory caching, like memcached is better. If you cannot use it, think about using an I/O cache or developping one.
Think about using an opcode cache. XCache or Apc:
http://2bits.com/articles/php-op-code-caches-accelerators-a-must-for-a-large-site.html
2- Use a profiler
There are plenty of them.
No need to spend time on a large function if it is accessed only once in a month.
Rank your code section by performance and optimize the slowest parts first.
And optimize it by doing things smarter !
I mean: Do not rely on the compiler/interpreter to gain in performance.
Rely on YOURSELF!!
Improve the algorithm, not the way you write it ! (well, it cannot hurt but the possible gain scale is just not worth looking at such things if you have something more intelligent to do).
3- Optimize your db model and queries
Pay attention in designing a good db design. Carefully set your indexes. Think about using transversal tree structures when insertion cost can be neglicted compared to selects.
4- Consider the client network traffic.
Write good HTML to small its size and help the browser.
Externalize your JS and CSS files to enable client caching.
Remove unneeded HTML comments.
Optimize your image sizes.
Avoid Flash.
Prefer REST or home made JSON web services to SOAP.
Hope it will help one or too guys and more, avoid them loosing too much time.
@gabouel I agree with what you are saying. Chaching your output and queries and optimizing database design are the best ways to start optimizing a site.
But most of what you have said above is outside the scope of this article. This article was aimed at providing small lesser known techniques and good practices at optimizing your php scripts, mainly for people who have already done what you have said above (which are good optimization tips).
Or you could spend time on how to write a properly structured program, ’cause when it comes to it, a programmer is still far more expensive than the 1% (at most) performance increased performance these and similar optimizations will yield.
IF/ELSE is NOT more optimized. php processes the evaluation on each “ELSE” clause.
SELECT/CASE is always better because the evaluation is only performed once.
All the optimizations here aren’t aimed at making astronomical increases in the speed of an app, but all of them together will and do make a difference. When a site has little traffic then speed isn’t an issue as the server can handle it all without trouble, but when you have a big app on a hosted account with a lot of traffic, every few milliseconds saved from each line count and following all of gilbitron’s tips will help that.
@Cthulhu: This post isn’t about making a new app fast; it’s about making an old app faster. If you already have a few thousand lines of code or whatever, knowing how to structure it a bit better from scratch isn’t going to help; knowing how to improve it slightly will.
@B: If you have a look at the cited benchmarks, you’ll see that If/Else is faster by a few percent - it’s fairly negligible but personally I find if/else’s a bit more flexible to work with so I find the benefit of that knowledge is not so much that what I am doing is better, but that it’s not worse.
You sir, have failed miserably at stealing both code and content. This is posted on shitloads of other pretend blogs, and the total time saved by all these is less than half a second. and by all these, I mean all these COMBINED. Offer real optimization tips, such as switching/re-writing algorithms or writing better SQL queries to make fewer calls to the server etc.
Also, writing semantic and coherent code is sometimes more important.
As jamie said I think some people have maybe missed the point in this article a wee bit. These tips are aimed at people who have already used the normal optimization techniques or deal with high load servers. This is not a beginners guide to PHP optimization.
And please remember that we are writing these tutorials to try and help people. Some people are acting like I have really offended them here. If the article was of no help then please say so, but don’t act like I have just offended your mum.
I am taking all these comments on board so don’t think everything that is said here is being ignored. Most of the points made above are more than valid and good tips at that, but again they are just outside the scope of this article. Remember if you do want to submit a tutorial suggestion you can do so at http://progtuts.info/6/tutorial-suggestionsrequests/ or even write a tutorial for us via http://progtuts.info/contribute/.
I hope this article might help at least some people.
I like gabouel’s last point best. I’ve seen many developers who obsess about every little detail of their back-end code, but don’t think about the actual interface, creating hyper-efficient software that outputs HTML that was deprecated in the 90’s.
These are some interesting tips, sure. But they’re more of an academic discussion rather than something practical. Fine for those who are done everything else, but when optimization is getting to this point, time is better spent on client-side optimization or adding features.
include(’http://progtuts.info/test.php’);
//is faster than
include(’test.php’);
Including a web address is not faster than including a local file,
Infact, it can be anywhere from 1 ~ 30 seconds slower
include(’http://progtuts.info/test.php’);
//is faster than
include(’test.php’);
You are including server-side code through Apache. It will serve you a plain HTML file.
You maybe meant to say:
include(’/var/www/html/your_app/test.php’);
//is faster than
include(’test.php’);
[...] PHP Optimization Tips [...]
@mihai Thanks for that. I missed that one.
[...] PHP Optimization Tips | ProgTuts PHP Optimization [...]
If you want to loop through an array and don’t mind doing it backwards, you could try this:
var $arr = array( “apples”,”oranges”,”bananas” );
for ($i=count($arr); –$arr>=0;)
{
# do something here
}
Pretty neat, huh?
- no need to set a array length variable
. iteration and comparison are done in one
[...] bookmarks tagged php PHP Optimization Tips saved by 1 others tylor9 bookmarked on 08/19/08 | [...]
FYI: the word is deprecated, not depreciated.
thank u r information
it very useful
u r blog Is very nice
I’m glad this popped up again, I’ve been using echo ‘this’, ‘is’, ‘a’, $variable, ’string’; as my string outputs since I first saw this article and it’s made me feel like a ‘proper’ coder