Even More 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!
Because I've already talked about the main, general, optimization tips, these ones will tend to be more specific and may not apply to everyone - nonetheless, it's worth a read in case you ever do come across these situations.
Here are tips 11-15:
11. is_numeric() vs. ctype_digit()
To see whether is_numeric() or ctype_digit() is the fastest method, I called each function 10,000,000 times. Here are the resuts:
is_numeric(): 9.943268 seconds
ctype_digit(): 11.801991 seconds
is_numeric() is 15.75% faster than ctype_digit()
It's worth using is_numeric() over ctype_digit() where it's appropriate to do so. Although a difference of 0.0000001858723 may seem small, it does all add up.
12. echo vs.print
It's often been said that echo is faster than print, simply because it doesn't return a value. To put this theory to the test, I called echo 'TEXT' 20,000,000, followed by print 'TEXT' 20,000,000 times. Here are the results:
echo 'TEXT': 8.571081 seconds
print 'TEXT': 8.585106 seconds
echo is 0.16% faster than print
Although echo is faster than print, it's not worth changing the way you code PHP. If you prefer print, there's no real reason to use echo instead.
13. Better conditional statements
When specifying a condition in an if statement, for loop, or elsewhere, think about it carefully. In PHP, if you done this:
if($var1 && $var2) {
}
The condition will be false if $var1 is false - it wouldn't need to check $var2. But, if $var2 was more likely to be false, it should come first:
if($var2 && $var1) {
}
To test this, I created two if statements. In the first statement, I put $var1 || $var2 as the condition, and, in the second, I put $var2 || $var1. The values of the two variables are generated randomly - $var1 is should be true about 75% of the time, while $var2 will be true 30% of the time. These were put into a loop which iterated 1,000,000 times. Theoretically, the $var1 || $var2 should be better, because $var1 is more likely to be true. Here are the results:
$var1 || $var2: 2.325065 seconds
$var2 || $var1: 2.367621 seconds
$var1 || $var2 is 1.797% faster than $var2 || $var1
Despite 1.797% seeming a small figure, it is high enough for you to think about your conditional statements. In different conditional statements, where they are maybe 4 varialbes involved in string, and number comparisons, this figure may increase further.
14. === (Identical) vs. == (Equal)
You may think, as I first did, that == is faster than ===. But, to my surprise, === was significantly faster than ==. I run if('string' === 'string) { } 10,000,000 times, followed by if('string' == 'string') { } another 10,000,000 times. Here are the results:
==: 4.194739 seconds
===: 3.510191 seconds
=== is 16.32% faster than ==
I guess that === is faster simply because it doesn't have to convert both sides to strings first. (I guess I was wrong: See Rob's comment). Obviously, there are situations where == must be used over ===.
15. intval('100') vs. (int)'100'
I had no idea which one these was going to be faster. To test them, I called each one 5,000,000 times. Here are the results:
intval('100'): 6.441137 seconds
(int)'100': 2.933663 seconds
(int)'100' is 54.45% faster than intval('100').
Although I had no expectations, the results were quite surprising. With a 54.45% speed difference, it's well worth using (int) over intval().
So that's the last of the "Faster PHP Scripts" tips for now. I might write another article so look out for it - it'll probably called "Even More Tips for faster PHP Scripts Continued" or some other ridiculous title.
Please comment and tell me what your favourite tips were - mine must be 15 and 14.
Tags: conditions, efficiency, micro optimization, Optimization, PHP












Come velocizzare i nostri script PHP / Melodycode.com - Life is a flash Said,
November 28, 2007 @ 7:04 pm
[…] navigazione e grazie per la visita!Ho appena letto un articolo molto interessante intitolato "Even More Tips for faster PHP scripts" dove vengono paragonati alcuni costrutti PHP sul piano delle performance. Aggiungerei come […]
Emanuele Said,
November 28, 2007 @ 10:04 pm
Nice tests. Thanks!
Bye,
Emanuele
roScripts - Webmaster resources and websites Said,
November 28, 2007 @ 11:15 pm
Making the web » Even More Tips for faster PHP scripts
Making the web » Even More Tips for faster PHP scripts
Ausome1 Said,
December 4, 2007 @ 9:22 pm
The only problem I see is your is_numeric vs ctype_digit.
$n = '1234.5';
var_dump(is_numeric($n)); // returns bool(true)
var_dump(ctype_digit($n)); // returns bool(false)
In the above example $n is a number. But see that decimal point? That’s not a numeric character, therefore ctype_digit($n) is false.
You'll need to make sure this what you are after as a result.
And on a side note.
There is one quirk with ctype_digit that may affect your choice about whether to use it.
When the string in question is empty, ctype_digit returns TRUE. However, when it is null, ctype_digit will return FALSE. Try out the code below to see what I mean.
Forex News Charts and Commentary Said,
December 18, 2007 @ 2:10 pm
echo vs. print
Even better speed results when querying SQL data.
Karl
Octopus Said,
December 18, 2007 @ 6:02 pm
These are great tips for langauges such as C++ which may be running engineering type calculations that need to be iterated 100s of thousands of times. In the case of PHP however, these differences really are quite trivial. The whole philosophy of PHP is different. Scripts are short and generally run once in order to deliver some fairly straight forward content. Needing to run a function 10 million times to even see a difference is proof that none of this is necessary. Even the most popular websites only see tens of thousands of hits in a day, but most of the time the web server is sitting idle.
Great advice for C++, for PHP its nice to know, but don't sweat it.
PHP kodu yazarken hız açısından nelere dikkat etmelisiniz. - katodivaihe Said,
December 19, 2007 @ 7:27 pm
[…] via : http://bitfilm.net/2007/11/27/even-more-tips-for-faster-php-scripts/ […]
Jach Said,
December 20, 2007 @ 5:04 am
Only really nice tip was intval() vs (int), which I give my thanks for (I've been using intval()). But as a previous commenter noted, you don't really need to optimize PHP, and as computers get faster and faster optimization will become insignificant for any language.
Alex Howell Said,
December 20, 2007 @ 1:05 pm
Point 15 is kinda trivial, because it's always faster to use language constructs over functions- that's always a point worth bearing mind.
As someone has already said- all these points are meaningless: if your site had that much traffic, you'd write it in a grown up language like .net as it's always going to be faster. When it gets to the point where you have millions of page hits, the speed increase you need will only be got from using a lower level language. And until we all have 80Mb pipes the slowest point will always be the failures of ethernet and the rendering speed of our browsers.
Having said that, if you are that desperate to speed things up, here are things which will noticeably help:
1) If you're doing image maniuplation, flush out resources you don't need. CPU is one bottleneck- RAM bcomes another if you use a lot of it.
2) Use language constructs over functions: e.g. $myarray[] = 'next val'; instead of array_push($myarray, 'newval');
3) Use predefined functions rather than home made ones. This is because of the way php is compiled into bytecode- using predefined functions will be a lot faster, and also a lot more thought will have been invested into each one then any individual developer can afford, making it faster and more secure.
3) Consider using output compression: an extra few seconds on the server, a lot fewer minutes downloading
4) Consider using a compiled php file cacher- saves the php file being compiled on the fly every time you hit refresh
5) Turn off HostnameLookups
Alex Howell Said,
December 20, 2007 @ 1:09 pm
Also; with regard to your testing, it would matter in your tests the kind of data you use. Picking random strings or integers might not give the best (most accurate) results because the underlying code will be designed to offer best performance over a range of most likely values. I would be interested to know what bank of data you used for these recursive tests- using the same value over and over again is not going to be a fair test of php's capabilities. Not to four significant figures, anyway.
Evan Said,
December 23, 2007 @ 4:11 am
I love that you ran echo and print 20,000,000 times each — that's great.
This is a handy little list, thanks ^_^
Teknoloji Haberleri Said,
January 3, 2008 @ 5:19 pm
Thanks for this subject…
Brian Rock Said,
February 16, 2008 @ 10:29 pm
While some of this may seem pedantic, I don't see the harm in benchmarking, testing, and optimizing php. I wouldn't spend a lot of time optimizing scripts, but it's an interesting exercise to consider.
On a side note, I came up with some other results for echo v. print. I ran 'echo "Hello World" 100,000 times. Took an average of 20 runs, and after two sets of tests I had average times of 10.8 seconds and 9.23 seconds. With the same set-up switched to print, I came up with averages of 8.77 and 8.95.
When I tested it, print turned out faster. When you've got a deviation of 0.16%, I'd hesitate to say "It's faster." Even with that many iterations, you've got a level of error involved.
Веб-обзор #11: Silverlight 2, стартапы, как создавали успешные проекты и типология социальных проектов. | Alpha-Beta-Release Blog Said,
February 25, 2008 @ 12:14 pm
[…] for faster PHP Scripts - сборник в трёх частях (2 и 3) различных небольших приёмов и техник для повышения […]
Rob Desbois Said,
February 25, 2008 @ 4:07 pm
Your reasoning for tip #14, "I guess that === is faster simply because it doesn't have to convert both sides to strings first.", is incorrect.
After compilation, if (a === b) will result in something like the following:
1. if typeof(a) is not typeof(b) return false
2. if a equals b return true
Similarly, if (a == b) will be something like:
1. if typeof(a) is not typeof(b) goto 4
2. if a equals b return true
3. return false
4. if typeof(a) is not string goto 8
5. convert b to string and store in c
6. if a equals c return true
7. return false
8. …
Simply, the non-identity equality comparison operator will have to do *more* work as it must convert the types to values which can be compared directly.
Otherwise, interesting tips but the speedups (#15) are unnecessary; PHP isn't a suitable language (IMHO) for a job where 1E6 times when it's likely not called more than a few times in a script.
Rob Desbois Said,
February 25, 2008 @ 5:39 pm
My apologies — brackets in last paragraph was meant to read (except #15); that's a good improvement I was unaware of
poste9 Said,
February 26, 2008 @ 2:05 pm
Can u test what faster loop we could use?
while increasing, while decreasing, for, foreach…
myme Said,
February 28, 2008 @ 2:06 pm
@Rob Desbois
a == b ALWAYS converts all values into Integer, even both are Strings
The Code
if ((string)'0×10' == (string)'16') echo 'True'; else echo 'False';
echo ',';
if (strval('0×10') == strval('16')) echo 'True'; else echo 'False';
will result in "True,True"
Tim Said,
March 10, 2008 @ 3:49 pm
String manipulation is slow, but the alternative is often doing lots of little bits of output. What is faster —
$a = " ; $i = 100 ;
do { $a .= 'x'; $a .= 'x'; $a .= 'x'; $a .= 'x'; $a .= 'x'; } while (–$i > 0) ;
echo $a, "\n" ;
— or —
$i = 100;
do { echo 'x'; echo 'x'; echo 'x'; echo 'x'; echo 'x'; } while (–$i > 0) ;
echo "\n" ;
— ?
Jon Gilbert Said,
March 26, 2008 @ 8:56 am
Interesting series of articles, thnx. Some things are common knowledge (aren't they folks?), but a few tips in there which are surprising and handy.
I cannot agree with Octopus that optimization is not important for php. The computing power required for a single page is usually low, but when working on high profile and high performance sites, optimization is crucial when hundreds of millions of requests are received on a dialy basis (see http://www.studivz.net/l/about_us/1/ - its in german, but maybe some readers can undertand it or at least put it through babelfish or google translate).
Best regards from Berlin.
Jon
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 29, 2008 @ 3:07 pm
[…] ho deciso di prendere spunto da tre articoli che trovai tempo fa su come ottimizzare la scrittura di codice PHP, verificare, e […]
Mike Said,
May 29, 2008 @ 3:38 pm
these optomizations are worthless unless you're getting more hits than Google, Yahoo, and YouTube combined.
How about some real optimizations to save some actual time, like making sure people know how to use data sctructures properly so they're not iterating over the same array more than once?
Performance evaluation in php | Menhir-effect blog Said,
September 21, 2008 @ 4:23 pm
[…] Even more faster php scripts […]
php optimization script « All about PHP Said,
October 23, 2008 @ 7:14 am
[…] because it doesn't have to convert both sides to strings first. (I guess I was wrong: See Rob's comment). Obviously, there are situations where == must be used over […]
Hello world! « All about PHP Said,
October 23, 2008 @ 7:17 am
[…] because it doesn't have to convert both sides to strings first. (I guess I was wrong: See Rob's comment). Obviously, there are situations where == must be used over […]
audio price car amplifier Said,
December 31, 2008 @ 3:27 am
ch car audio amplifier audio car parts amplifier