Tips for faster PHP scripts
Hey there! Welcome to Making the Web - my personal blog about website development. Feel free to subscribe to my RSS feed to keep up with the latest. Alternatively, subscribe by email. Hope you enjoy this article!
More Tips for faster PHP scripts
Even More Tips for faster PHP scripts
I have listed my top tips for writing faster (optimized) PHP code:
1. Multiple arguments with echo
When you use echo, you probably use something like this:
echo $variable1 . 'string1' . $variable2 . $variable3;
But, you may be forgetting that echo can take multiple arguments. So you can write it like this:
echo $variable1 , 'string1' , $variable2 , $variable3;
Passing multiple arguments to echo is faster than joining the strings first, and then passing them to echo. I done a little test in PHP. I echoed 10 different strings 500 thousand times, firstly with the concatenation (joining) method, and then with the multiple arguments method. Here are my results:
Time for concatenation method: 37.83755 seconds
Time for multiple arguments method: 37.68789 seconds
Time saved: 0.15966 seconds; 0.396%
As you can see, the difference is very small. It is not worth going over all your old PHP scripts and changing the dots to commas, unless you are extremely desperate for speed. It is more a case of preference, than there being a best way.
Oh, and another small tip (without it's own number): use echo instead of print - it's faster!
2. Reduce Function Calls
Now it may seem obvious, but many scripts have unnecessary calls to functions. Look at this:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
for($a = 0; $a < sizeof($array); $a++) {
// Do something
}
How many times is the function sizeof() called? If you think once, you are wrong. It is actually called 21 times - once for every iteration. You should do the function call (or calculation) outside of the for loop, assign the value to a variable and use the variable in the for loop.
I done another test. In each test, I had an array with 10,000 elements, and a for loop with 10,000 iterations. In the first test, I had sizeof($array) within the for loop - so it would be called 10,001 times. In the second test, I got the value sizeof($array) and assigned it to the variable $no. I then used $no in the for loop. Test 2 should be faster than test 1, because sizeof() is called 10,000 times less. Here are my results:
Test 1 (sizeof() called 10, 001 times): 0.02784 seconds
Test 2 (sizeof() called 1 time): 0.01278 seconds
Time saved: 0.01506 seconds; 54.095%
3. Do you really need to keep everything?
Some scripts assign values to variables when they don't need to. Take a look at this code:
$string = 'String for Output';
echo $string;
If you are only going to use $string once, do we need it? No, we just need it's value. If we keep it as a variable, it is going to stay in the memory for the entire script. This would be better:
echo 'String for Output';
If you do need to use a variable, you might want to consider using unset() to destroy it.
4.Using single quotes
When using strings in PHP, you have the choice of either double quotes ( " ) or single quotes ( ' ). With double quotes, everything in between is parsed (so you can use variables between them). With single quotes, the string is not parsed. So, this code…
$string = 'Hello';
…is better than:
$string = "Hello";
I done a test to see how much difference this makes. In the first test, I assigned a string to a variable 50,000,000 times using double quotes. In the second test, I assign a string to a variable 50,000,000 times, but this time with single quotes. Here are the results of my test:
Double Quotes: 51.74447 seconds
Single Quotes: 51.38412 seconds
Time saved: 0.36035 seconds; 0.696%
The difference is small, but a saving nonetheless. I would always recommend using single quotes over double quotes.
5. str_replace() vs. ereg_replace() and preg_replace()
If you do not need to use regular expressions when replacing strings, you should use str_replace() instead of other functions. This code…
str_replace('search', 'find', 'searched string');
…is faster than:
ereg_replace('search', 'find', 'searched string');
Obviously, it is necessary to use ereg_replace() (or preg_replace(), which is often a faster alternative) when using regular expressions. I done an experiment to see how much difference there is. I replaced a string 5,000,000 times with ereg_replace(), 5,000,000 times with preg_replace(), followed by 5,000,000 times with str_replace(). I replace the same string, not using regular expressions. Here are my results:
ereg_replace(): 26.65647 seconds
preg_replace(): 25.18324 seconds
str_replace(): 10.26872 seconds
Time saved (against ereg_replace()): 16.38775 seconds: 61.478%
Time saved (against preg_replace()): 14.91452 seconds: 59.224%
So, it's better to use str_replace() rather than ereg_replace() and preg_replace(), when you are not using regular expressions.












Jeff Said,
September 2, 2007 @ 8:57 pm
Hey great tips, thank you so much for sharing. I really like the way you included the render times as well to back-up your claims. Most of them pretty straight up; but the for loop sizeof() ; l do that all the time and l never thought about that - so l'll definitely change my ways. Thanks!
Keep them coming!
HoboBen Said,
September 3, 2007 @ 2:54 am
That was interesting - I didn't know about the single quotes one (pt. 4)
Thank you!
Brittany Said,
September 3, 2007 @ 4:19 am
With all due respect, I think that most of these optimizations are a waste of time. #2 is a good idea, but it's also a good general rule of thumb for any programming language. With the exception of tip #2, most of these 'optimizations' do not offer a real improvement. I bet you could get the same time differences simply by running the script twice.
The single best speed optimization would be to use C++.
DGM Said,
September 3, 2007 @ 5:15 am
These are silly optimizations that pale in comparison to algorithmic issues. What's a millionth of a second if you have a O(n^2) algorithm? Look up premature optimization, and Big O notation.
Napolux Said,
September 3, 2007 @ 6:49 am
A really useful post. Thank you!!!
Jaspal Singh Sutdhar Said,
September 4, 2007 @ 5:22 am
Thanks, great tips.
Jnomis Said,
September 5, 2007 @ 5:16 pm
You have done us a service by testing some of the assertions.
You have done us no service by stating that assertions with a fraction of a percent matter.
Juan Timana Said,
September 16, 2007 @ 7:45 pm
Really nice and useful article, great job!
48 links PHP (perché 50 “fa brutto”) | Napolux.com Said,
September 25, 2007 @ 11:12 am
[…] Tips for faster PHP scripts […]
JOKERz Said,
September 25, 2007 @ 4:05 pm
Nice tips!!!
Dl. Petcu Said,
September 25, 2007 @ 8:01 pm
that's a very nice usefull article
Mgccl Said,
September 25, 2007 @ 11:20 pm
very nice. check out mine article..
php speed freaks
Master Employment Said,
September 26, 2007 @ 5:16 pm
The article is very interesting. Thanks for it, but unfortunately I agree with Brittany. Most of these optimizations are a waste of time, and may transform your code hard to read. For instance when you scan (read) a code; it will be much easer to understand:
for($a = 0; $a
Master Employment Said,
September 26, 2007 @ 5:17 pm
for($a = 0; $a
Master Employment Said,
September 26, 2007 @ 5:18 pm
The article is very interesting. Thanks for it, but unfortunately I agree with Brittany. Most of these optimizations are a waste of time, and may transform your code hard to read. For instance when you scan (read) a code; it will be much easer to understand:
for($a = 0; $a < sizeof($array); $a++) {
// Do something
}
Then
$size_of_array = $array;
for($a = 0; $a < $size_of_array; $a++) {
// Do something
}
No 5 is really very useful.
RonnyZenn Said,
September 26, 2007 @ 9:02 pm
Thank you for tips! Don't know if i ever use it, but nice to know
Cj B Said,
September 28, 2007 @ 9:02 pm
Wow, great tips!
Ab Said,
October 7, 2007 @ 12:10 pm
Very useful tips, thanks!
Il meglio della settimana - 49 | Napolux.com Said,
October 28, 2007 @ 11:45 am
[…] Buona domenica a tutti! Mass attack (videogame) Wallpaper bellissimi ad alta risoluzione CamStudio (come non citarlo?) Instant.JS Tips for faster PHP scripts […]
Kent Schnepp Said,
November 19, 2007 @ 5:31 am
Great post! Keep them coming!
Consejos para mejorar la velocidad de nuestros scripts PHP | aNieto2K Said,
November 19, 2007 @ 11:33 am
[…] En PHP, hay muchas formas de hacer las cosas, pero unas son mejores que otras, en este artículo vemos cuales son algunas de esos métodos que usamos y que podríamos optimizar. […]
SylverStyle Said,
November 19, 2007 @ 7:06 pm
here are some more PHP optimization tips
http://ecastr.com/phoenix/blog/details/advanced_php_optimization_tips_chapter/
http://ecastr.com/phoenix/blog/details/advanced_php_optimization_tips_chapter_2/
Fabrizio Said,
December 11, 2007 @ 9:03 pm
I think that in a website the major delays are in the database and filesystem, first optimize database (adding indexes, for example),file access, then optimize code
Make It Up As You Go » Blog Archive » Faster PHP Scripts Said,
December 12, 2007 @ 12:16 am
[…] Bitfilm lists 5 tips for faster PHP scripts. […]
links for 2007-11-20 at tech.kedesfase.com Said,
December 12, 2007 @ 9:40 am
[…] Making the web » Tips for faster PHP scripts Los trucos parecen un poco tontos, pero pueden llegar a ser muy valiosos para acelerar las cosas. (tags: programacion php) […]
Arnold Daniels Said,
December 12, 2007 @ 11:24 am
for ($i=0, $c=sizeof($a); $i
Arnold Daniels Said,
December 12, 2007 @ 11:29 am
for($i=0, $c=sizeof($i); $i<$c; $i++) {
…
}
Seems perfectly readable to me.
mriza Said,
January 1, 2008 @ 9:54 am
Good one, i give it 4 stars.
Sujith Said,
January 10, 2008 @ 5:32 am
really good one , can i have your article content ,if so i put the same i to my web site ………awaiting for your postive reply
Sujith Said,
January 10, 2008 @ 5:33 am
really good one , can i have your article content ,if so i put the same in to my web site ………awaiting for your postive reply
Brendon Said,
January 10, 2008 @ 8:06 am
Yes you can use the content - just link back to http://bitfilm.net/2007/08/24/tips-for-faster-php-scripts/ (preferably just before the content)
EdgarPE Said,
January 15, 2008 @ 11:47 pm
Have to agree with Brittany and others, that these optimization tips are not so useful.
If you want real performance then do these in this order:
A) save on SQL querys, cache query results
B) save on string manipulation, cache parts of HTML
C) save whole page generation, cache full pages
D) save on PHP interpreter overhead, serve pure HTML files (regenerated regularly, even every minute if you want). You can maintain nice url-s with .htaccess.
For caching various data I recommend APC, but memcache, Xcache and Zend Optimizer are just fine too.
Dwayne Charrington Said,
February 12, 2008 @ 5:23 am
Being a professionally employed PHP developer for some time now I can honestly say that although the speed increases are minor. If you combine all of these tips together, your script loading time will be dramatically decreased ten fold.
The Internet would be a faster place for PHP if everyone took the extra time to optimise their scripts.
- Dwayne Charrington.
http://www.dwaynecharrington.com
nic Said,
February 12, 2008 @ 1:07 pm
This is an interesting article. I probably will not ever use it. But it is still interesting to know. Thanks!
Making the web » More Tips for faster PHP scripts Said,
February 12, 2008 @ 4:59 pm
[…] post is part 2 of a 3 part series. For the other parts, visit these posts: Tips for faster PHP scripts Even More Tips for faster PHP […]
Richy’s Random Ramblings / PHP: Making faster PHP scripts Said,
February 18, 2008 @ 6:25 pm
[…] Page one […]
Веб-обзор #11: Silverlight 2, стартапы, как создавали успешные проекты и типология социальных проектов. | Alpha-Beta-Release Blog Said,
February 25, 2008 @ 12:13 pm
[…] Tips for faster PHP Scripts - сборник в трёх частях (2 и 3) различных небольших приёмов и техник для повышения производительности ваших РНР скриптов, причём это не только банальные приходящие на ум сразу решения, но и тонкости, вроде отличия функций проверки типов (is_numeric или ctype_digit). Совтую прочитать, конечно, десятки процентов увеличения производительности вы сразу не получите, но вполне возможно, что от многих узких мест можно избавится или хоть бы сгладить их влияние. […]
Dave Said,
February 26, 2008 @ 10:44 pm
As far as single-quote string versus double-quote strings are concerned, I'd be interested in seeing the difference between:
$world = 'world';
echo("Hello $world !");
and:
$world = 'world';
echo('Hello '.$world.' !');
I strongly suspect that there would be very little difference between them but you just can't be sure until you have actually tried it.
10 more tips to make your PHP application scream - Part 2 of N :: Jaisen Mathai Said,
March 1, 2008 @ 9:53 am
[…] http://bitfilm.net/2007/08/24/tips-for-faster-php-scripts/ […]
Jaisen Said,
March 1, 2008 @ 6:44 pm
@Dave, a 3rd comparison should be
$world = 'world';
echo('Hello ',$world,' !');
Since using commas doesn't require PHP to do any concatenation and just passes 3 parameters to echo.
sanjuro Said,
March 20, 2008 @ 4:03 pm
Nice tips, the first one surprised me. Is it true that assigning concatenated strings to a variable and then calling it with echo is faster than echoing them directly ?
Dicas para um PHP mais veloz « DUODRACO Said,
April 12, 2008 @ 4:49 pm
[…] tips-for-faster-php-scripts more tips for faster php scripts even more tips for faster php script […]
Consigli per script PHP più veloci Said,
April 21, 2008 @ 7:51 pm
[…] ho deciso di prendere spunto da tre articoli che trovai tempo fa su come ottimizzare la scrittura di codice PHP, verificare, e […]
tobto Said,
May 12, 2008 @ 9:44 am
nice post - gives smart ideas for developing - thx!
Mike Said,
May 29, 2008 @ 3:21 pm
How about some optimizations that really matter? .4 seconds over 50,000,000 iterations would save Wikipedia an average of .4 seconds per day.
Now, the average page load time for Wikipedia is 1.9 seconds.
Saving .4 seconds over the day means each user will save .000000008 seconds.
Noticeable? No.
Another way to look at it is at their current rate, by saving .4 seconds per day, they get one additional page load every 5 days for the same exact amount of processing time it took them to do it otherwise.
Now put that into a script being written and run for joe schmoe developer who's site gets 12,000 hits per year. It'll take that site 41,666 years to see that same .4 second save in time.