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!
This 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 scripts
Here's the list:
6. Pre-increment is faster than post-increment
Try to pre-increment, rather than post-increment, where possible. It is faster because post-increment creates a temporary variable while in the process of incrementing. So, this:
++$var;
…is faster than this:
$var++;
This rule also applies to decrementation as well. To test this assertion, I created two for loops. The first for loop used the post-increment option, while the second for loop used pre-increment instead. The total number of iterations was 10,000,000. Here are the results:
Post-increment: 2.148 seconds
Pre-increment: 1.692 seconds
Time saved: 0.456 seconds; 21.23%
7. Regular Expressions for input validation?
It is always a good idea to try and avoid regular expressions, where possible and practical. There are functions in PHP which will do exactly what some regular expressions do, but faster. Take this example:
if(ereg('[0123456789]', $number)) {
// Is integer
}else{
// Is not integer
}
It is much faster to do this instead:
if(ctype_digit($number)) {
// Is integer
}else{
// Is not integer
}
To test this, I used ereg('[0123456789]', $number) 1,000,000 times, followed by using ctype_digit($number) 1,000,000 times. Here are the results:
Regular Expressions: 2.401 seconds
ctype_digit: 0.985 seconds
Time saved: 1.416 seconds; 58.98%
8. split() or explode()
The split() function supports regular expressions, while explode() does not. It is often faster to use explode() when you do not need to use regular expressions.I done yet another test. I used split() to split a string without regular expression requirements, and then used explode() to split the same string. I repeated this 1,000,000 times. My results are:
split(): 5.453 seconds
explode(): 3.556 seconds
Time saved: 1.897 seconds; 34.79%
9. Use time() rather than date('U')
When you want to get the current Unix timestamp, it is faster to use time() rather than date('U'). To test this, I used the time() function 100,000 times, followed by date('U') 100,000 times. My results are as follows:
date('U'): 19.162 seconds
time(): 0.057 seconds
Time saved: 19.105 seconds; 99.7%
10. Fastest type of loop
In PHP, there are a number of loops available for you to use. There are while loops, do-while loops, and for loops. To see which one of these were fastest, I used each of them to perform 100,000,000 iterations. These are the loops which I used:
while(++$a<100000000){}
for(;++$a<100000000;){}
do{}while(++$a<100000000)
Here are my results:
while(++$a<100000000){}: 15.519 seconds
for(;++$a<100000000;){}: 17.577 seconds
do{}while(++$a<100000000): 13.744 seconds
As you can see, my results show that a do-while loop is 21.81% faster, compared to a for loop.













Making the web » Tips for faster PHP scripts Said,
September 7, 2007 @ 4:26 pm
[…] For more, see More Tips for faster PHP Scripts. […]
Hernan Said,
September 21, 2007 @ 4:15 pm
Thanks you for your tips. I was programming in php for 5 years and this is the first time I see tips on efficiency.
I was collecting websites with relevant tips on php development. I will include a link to your site in my community (check it clicking on my name)
Thanks a lot for this info.
useful Said,
September 22, 2007 @ 8:33 am
If you want speed casting is faster that both ctype_digit and ereg
(int) $number;
5.11sec
vs
ctype_digit($number);
9.43sec
Hispatial Said,
September 22, 2007 @ 11:00 pm
Great tips, the date and time seem like the biggest difference.
Ryan Said,
September 23, 2007 @ 8:07 pm
While it's cool and all to benchmark these types of things, you really won't see much of a difference with any web app doing this. If you have to run your benchmarking scripts a million or hundred thousand times to see a slight difference, it probably isn't worth it.
Real performance gains are through caching (opcode and after heavy computations), tweaking your database, using database replication and profiling your code. Rasmus Lerdorf has some great slides on how to increase PHP's performance.
It's the 80/20 rule. 20% of your code is taking up 80% of the computation time. Focus on that first before tweaking looks and little function calls.
All in a days work… Said,
September 24, 2007 @ 2:25 am
[…] Tips for lightning fast PHP sites sizeof vs count, is_int vs is_integer, chop vs rtrim, doubleval vs floatval, fwrite vs fputs, implode vs join, ini_alter vs ini_set, Pre-increment faster than post, no regex, split() vs. explode(), use time() vs. date('U'), do-while is fastest loop (tags: PHP) […]
48 links PHP (perché 50 “fa brutto”) | Napolux.com Said,
September 25, 2007 @ 11:12 am
[…] More Tips for faster PHP scripts […]
Master Employment Said,
September 26, 2007 @ 5:22 pm
Cool, thanks, I thought that FOR is faster then WHILE and DO. Will use DO from now on
SiteVoter Link Community Said,
September 30, 2007 @ 7:36 pm
More Tips for faster PHP scripts
At the moment that a website is getting more and more traffic scripts optimizations are very important. Because we developer are often lazy we don't care so much about code optimizations. This second blog shows some great examples how to speed up the …
Havvy Said,
October 4, 2007 @ 3:01 am
Things like this can save a lot of time on sites that get over 100k hits a day to there website. Useful for popular websites.
atomicoz Said,
October 5, 2007 @ 9:11 am
Great article, I didn't know that post-increment was faster.. Might as well start using it since it's slightly faster.
Most others I already knew about
Aaron Said,
October 6, 2007 @ 3:33 pm
For the most part, efficiency comes from using things the way they were meant to be used.
Animesh Said,
October 18, 2007 @ 8:31 pm
Can you compare echo and print for me? I was using print (since nobody mentioned echo is faster).
Updates From Sam Jones » Blog Archive » links for 2007-10-19 Said,
October 19, 2007 @ 4:24 pm
[…] Making the web » More Tips for faster PHP scripts (tags: php) […]
Faster PHP Scripts » Programmers Kit Said,
October 20, 2007 @ 2:03 pm
[…] Faster-php-scripts […]
Valerie Said,
October 20, 2007 @ 2:07 pm
Thanks for the great information!
Faster PHP Scripts
Jeff Said,
October 21, 2007 @ 2:34 am
I keep reading sites, I know PHP isn't rocket science, but I have so much to learn. Thanks for the article.
Victor San Martin Said,
November 19, 2007 @ 12:42 pm
nice tips.
Januarius Said,
November 21, 2007 @ 2:43 am
Surprisingly, unless it is possible so to be expressed about such site? Yes it, it is simple super! There is no only a section Sites
. Kiss
Joakim Nygard Said,
November 30, 2007 @ 8:17 pm
As for loop comparison remember that do{}while() _always_ execute at least once, whereas for and while will only execute if the statement is true on entering the loop.
In other words, do is not always interchangeable with for or while loops.
Make It Up As You Go » Blog Archive » Faster PHP Scripts Said,
December 12, 2007 @ 12:19 am
[…] The Web lists 15 tips for faster PHP scripts between three different […]
Johny Said,
December 17, 2007 @ 5:12 pm
Thanks a lot , for the valuable information
Ryan Said,
December 18, 2007 @ 3:35 am
Thanks for the tips! They will help a lot while I'm learning php!
Alex Howell Said,
December 20, 2007 @ 1:19 pm
Re: Point five: it might be pointed out that pre incrementing and post incrementing return different values: pre incrementing returns the incremented value, post the original value.
Re: Point six:
What exactly are you testing? Are you incrementing one variable ten million times, or incrementing one value a million times? Or a range of values a million times? A benchmark of iterating from 1-1,000,000 isn't accurate because no-one is ever going to do that- PHP's designers wont have optimized the language for that.
Going from 1 to -1,000,000 will be different from 1,000,000 to 1 because the underlying data type has to be changed from unsigned to signed, which has a memory overhead.
Specifying whether the var is an int or a float will make a difference. I would also imagine that there will be different data types used for larger numbers (floats, doubles, reals etc) which will each have different performance characteristics.
The test is only meaningful if it is done with a realistic scenario.
Re Point 7:
As the manual gracefully points out; preg is most often faster than ereg in any case. It's actually quite a useful thing to have around.
Alton Said,
January 18, 2008 @ 5:42 pm
Great info for a nooB like me. Thanks for the article.
Making the web » Tips for faster PHP scripts Said,
February 12, 2008 @ 4:45 pm
[…] post is part 1 of a 3 part series. For the other parts, visit these posts: More Tips for faster PHP scripts Even More Tips for faster PHP […]
Dave Said,
February 26, 2008 @ 10:36 pm
Apart from the date("U") vs. time() thing, none of those improvements are worth the time it takes to even think about them.
It's great that you have taken the time to prove that there is no practical difference between a for() loop and a while() loop. It's always worthwhile double checking to make sure your guesses are correct. What this shows is that you should write your PHP for readability and maintainability and use code profiling tools afterwards to optimise only where it is needed.
You could spend weeks rewriting all your code to use do…while() loops instead of for() loops and end up saving a grand total of a minute of CPU time each day. If you had spent the same time using XDebug you would have realised that 90% of the page generation time is spent in mysql_query() calls and you should have been optimising your SQL or caching the results.
When I find code that is causing problems because it's taking too long, it is usually something like a for() loop that iterates over an entire database table and discards 90% of the rows where it would be much more efficient to rewrite the SQL query to only return the 10% of the rows you actually want. Sometimes it's a snippet of code that writes and reads from the same database table, meaning that when you have lots of instances of this code running, they all have to wait for the table to be unlocked. (MyISAM can't do concurrent reads and writes) Sometimes it's PHP writing to a file over an NFS mounted directory that several webservers all write to.
When you're optimising code, run benchmarks, run profiling tools and pick the low-hanging fruit.
…and seriously, who would use date("U") instead of time() ?
Funciones PHP: Optimizar c Said,
March 6, 2008 @ 1:22 pm
[…] Separaciones: split() permite utilizar expresiones regulares, mientras que explode() no. Intenta utilizar explode siempre antes que la funci
Веб-обзор #11: Silverlight 2, стартапы, как создавали успешные проекты и типология социальных проектов. | Alpha-Beta-Release Blog Said,
March 6, 2008 @ 10:09 pm
[…] for faster PHP Scripts - сборник в трёх частях (2 и 3) различных небольших приёмов и техник для […]
Consigli per script PHP più veloci Said,
April 21, 2008 @ 7:52 pm
[…] ho deciso di prendere spunto da tre articoli che trovai tempo fa su come ottimizzare la scrittura di codice PHP, verificare, e […]