Fast PHP
by Justin Silverton
The following methods can help improve scalability with php applications.
1) object code caching
Each time a request comes to your server for a php script, it has to go through the compiler and then execute the object code. If this is cached, the 1st step is skipped and you end up with a faster and more responsive script.
There are many object code caching packages available on the Internet (some free, some commercial):
A) Ioncube: http://www.ioncube.com/
B) Zend Encoder: http://www.zend.com/products/zend_safeguard
C) Turckl MMCache: http://freshmeat.net/projects/turck-mmcache/
2) Template systems
Template systems provide a different type of caching. Content caching. Template systems work well in a situation where there is static data on one or many of your pages that doesn’t have to be reloaded. Caching systems also provide a separation of code and html, which will not only improve completion time of the overall project, but make it easier for future improvments. Most template systems for php are available for free:
A) Smarty Templates: http://smarty.php.net/
B) Pear Templates: http://pear.php.net/package/html_template_it/redirected
C) PHP savant: http://phpsavant.com/yawiki/
3) Distributed object caching systems
The most widely used system of this type is memcached (http://www.danga.com/memcached/).
This type of system makes your overall site faster by caching the majority of your database data into a large memory pool.
an interesting excerpt from their site:
“Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss.”
4) PHP variables that can be set
variables_order = ‘GPC’
register_argc_argv = ‘Off’
register_globals = ‘Off’ (this is a good idea to keep off for security purposes as well)
always_populate_raw_post_data = ‘Off’
magic_quotes_gpc = ‘Off’
Disable Error Logging. This is a good idea to keep on when you are developing your scripts, but it has been known to decrease overall performance.
Use IP address to access your database. Although this is sometimes not possible, you will get a slight boost in lookup speed if the IP address is used to access your database rather than its hostname.
5) Output Compression
Almost all browsers these days support something called gzip compression. Gzip compression can decrease the overall size of your output by up to 80%, but with a tradeoff: cpu usage will go up by around 10%. The benefit of using this compression type is the fact that not only will your bandwidth be decreased, but your pages will load faster.
enabling it in php (add the following lines to php.ini):
zlib.output_compression = On
zlib.output_compression_level = (level) (where level is 1-9. Youy may want to try different values to see what is best for your system).
if you are using apache, you can also enable the mod_gzip module. It is highly configurable, with the ability to modify output based on MIME types, files, or browser settings.
6) Other things that may help
when using a database, only retrieve the data that you are actually going to use. This may sound like a no-brainer, but I have often times worked on projects where the original programmer used (select * from mytable) when they could have used (select fieldIneed from mytable).
index database tables whenever possible
Learn more about this Here
specific language tricks
An interesting blog article I found mentions many interesting tricks that can be used: http://ilia.ws/archives/12-PHP-Optimization-Tricks.html
an article on zend.com about measuring performance: http://www.zend.com/zend/trick/trick-optimizing-php.php
58 Comments so far
Leave a reply






TurckMMCache is no longer maintain. eAccelerator is a fork of it and this project live.
Thanks for the information!
[…] Jaslabs: High performance php - Fast PHP September 4th, 2006 […]
[…] Jaslabs: High performance php Fast PHP September 4th, 2006 […]
Don’t forget APC: “APC is a free, open, and robust framework for caching and optimizing PHP intermediate code.” — http://pecl.php.net/package/APC
I Would have liked to see PHPTAL in the template section.
If you want to edit your templates in a WYSYWIG, PHPTAL is ideal as it uses attributes that do not break the scemantics of the XHTML.
TinyButStrong is another template that supports page caching.
Due to its dynamic nature, its non-cached execution speed is not impressive, however it speed up development considerably.
If performance is really critical but cache is out of question, Smarty and PEAR_Flexy allows compilation of template.
But when you’re compiling template, you may consider using straight PHP instead of going through another system.
Profiling is a must in optimisation & scaling. If you’re not attacking the source of problem you’re really not helping much.
Almost all PHP debugger supports profiling, but I personally found XDebug the easiest to use.
Most op-code cache also supports in-PHP caching of data. This can be utilised to cache static data like configurations or results of complex calculations.
Since disk is the bottleneck of modern computer, it also helps if number of source files is reduced. The performance gain can be considerable on a strained server that miss disk cache a lot.
Quick and enjoyable read, thanks.
You really must mention APC as it will be bundled with PHP 6
I’m suprised you didn’t mention APC. It seems to be way more popular than the other opcode caches you’ve mentioned and seems to be well maintained. I’ve heard rumors that it will be included into php6.
For output compression, mod_gzip is meant for apache 1.x mod_deflate was introduced for apache 2.x.
Disabling error-logging shouldn’t be recommended/suggested IMHO. Even in a well tested environment, errors/exeptions may still occur. A production website in general will have more permutations of events happening, thus a higher chance for errors. Good developers would proactively scan through error logs and fix it.
A much better (free/open source) caching system is APC. It’s in PECL, so it’s well supported and easy to install and use. It’s also maintained by a number of very well known PHP people, so I highly recommend it.
One thing to always remember is that premature optimisation is the root of all evil - only optimise things after you’ve benchmarked and found out EXACTLY where the bottleneck is. Another commenter above recommended XDebug which is fantastic for this.
–Simon
[…] read more | digg story […]
> Use IP address to access your database.
If your application and database share the same server, it’s faster to use a socket (instead of TCP/IP). You can accomplish this by specifying the socket manually, or simply connecting to the named “localhost” instead of 127.0.0.1 will achieve the same effect.
Wisdom of the crowds: http://trac.lighttpd.net/xcache/wiki/
It should be noted, that generally PHP is very fast - and its not the bottle neck, I/O is the bottleneck things like databases are where your site will slow down - if you are having to use things like eAccelerator or APC to speed up your PHP code, it would probably be more helpful to do a code review of your bottleneck pages, or if that doesn’t work - get more servers.
Also if you are having I/O problems, things like Memcached are life savers - and I strongly suggest using it.
[…] Here is an article that details 6 things that you can try in an attempt to make your PHP scripts faster! Hey Erik can this help you with your Senior Project?read more | digg story Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages. […]
eAccelerator is a little buggy, and can crash the server easilly… So I wouldn’t really advice anyone to use it
[…] Improve scalability with php applications. […]
Point is: php does not scale for very large applications. Use a language like Java for real large scale distributed systems.
Php is perferct for smale scale websites.
Good stuff. Thanks for the info!
[…] Jaslabs shares six key points on improving the speed of your dynamic PHP scripts including: object code caching, template system, distributed object caching system, turning off some global PHP variable settings, output compression and database query optimization. Listen to this post […]
You should check out Phalanger.
http://www.codeplex.com/Phalanger
It integrates PHP with ASP.NET, pre-compiling your PHP into MSIL, the same way eAccelerator and others pre-compile scripts. The difference is, it’s done by ASP.NET, and your scripts run on IIS6. With your scripts running on ASP.NET, they’re running managed which protects you from a great deal of security issues.
As for performance, I suggest you give it a try, because our tests show PHP running under ASP.NET under IIS6 under Windows 2003 completely destroys the same hardware running PHP with eAccelerator under Apache Linux 2.6 or FreeBSD. Sounds hard to believe, but we’re a shop full of linux/unix guys and all our stuff is currently on Apache and we gave ASP.NET a chance at running our PHP and the results were stunning.
Phalanger gives you the ability to use the .NET framework in your PHP scripts, and to use the code behind model of ASP.NET, but you don’t have to use that stuff if you don’t want to! It is 100% compatible with existing classic style PHP scripts, and PHP modules.
I’m no microsoft fanboi, but if you’re a real developer you shouldn’t be a unix fanboi either, you should test things out and see what works best for you. I highly recommend you test Phalanger with your existing PHP codebase.
[…] High Performance PHP (NÖRDAdót) […]
Thanks for the great tips.
Good stuff. Two small things that didn’t get mentioned but can have a big effect on large applications: includes and php’s parsing model.
Includes (and requires) can take increase load time dramatically. While they’re good for code separation, they suck on performance. Use them carefully.
PHP’s parsing model is interesting and you can get some performance gains by knowing how it works. Make sure you use single quotes as much as possible since PHP does not parse anything inside of them. This is really useful when accessing array elements. Seems like a small tweak but can save a ton on processing and can increase speed when you’re working with large arrays.
[…] 6 Ways to Make PHP Scripts Lightning fast! Just found this article over at digg - thought it’d be of some use to people […]
FastPHP y métodos para escalar aplicaciones PHP…
Justin Silverton publico en Agosto un artículo sobre FastPHP y métodos para mejorar la escalabilidad de aplicaciones PHP que me ha gustado y paso a traducir:
1) Cache de código objeto
Cada vez que una petición llega a nuestro servidor a por un sc…
The Zend product is called the Zend Accelerator. It is a part of the Zend Platform(http://www.zend.com/products/zend_platform)
[…] Jaslabs: High performance php » Fast PHP The following methods can help improve scalability with php applications (tags: php caching optimization) […]
[…] Jaslabs […]
I’d like to say that using template systems is slow itself! And why we are using them? It’s just a voice of the crowd!
Read a bit of PHP’s history. PHP is a great template engine itself. Try doing the same you’ve done with, for example, Smarty with pure php and ob_*() functions. You will see the difference.
don’t forget xcache http://trac.lighttpd.net/xcache/ (which also exposes an interesting api for caching variables and stuff, dunno if the others do)
[…] 6 things you can try to make your php scripts fast!read more | digg story […]
[…] Jaslabs: Fast PHP […]
[…] Programming: 6 Ways to Make your PHP lightening Fast A guide to optimizing your php scripts to reduce load times and increase performance. […]
[…] Šio savaitgalio skaitinai: Stiff asks, great programmers answer The 5 Books that Every Programmer Should Read Fast PHP Susiję straipsniai:while vs. forSavaitgalio skaitiniai #3Savaitgalio skaitiniai #2 […]
“I’d like to say that using template systems is slow itself! And why we are using them? It’s just a voice of the crowd!
Read a bit of PHP’s history. PHP is a great template engine itself. Try doing the same you’ve done with, for example, Smarty with pure php and ob_*() functions. You will see the difference.”
Templating systems are not that slow. Smarty by itself might have some more overhead than some of the other templating systems, but caching more than makes up for it.
Another good reason to use templates is a separation of code and design. If you have an application that is used by many people and needs updates (Security or otherwise), templates are a must.
[…] Good List OF PHP Speed Tips […]
[…] Jaslabs: High performance php » Fast PHP (tags: php) […]
Justin Silverton,
Yes, when it comes to multiuser systems it’s good to use some kind of a safe solution but PHP itself can provide such safety with it’s safe mode.
Considering code and design separation I can not agree. We can separate code and design by using pure PHP. Just getting all the data in our class, assigning it to class fields and then including a PHP-template. It PHP template we can use field ?>. Or for someone who likes shortcuts there is also a good solution: short tags. Just use field?>.
Another great disadvantage of third party template systems (I’ve used Smarty for 2 years) is that we need to learn new programming laguage.
Why just not to write field ?> instead of {$field}?! It’s just the same meaning!
[…] Jaslabs: High performance php » Fast PHP (tags: php) […]
[…] Here are what I judge to be the top 14 Digg.com submissions for the last month, in the programming category. These are excellent free training and learning resources that will teach you techniques for the following programming technologies: Ruby on Rails, MySQL, PHP, Ajax, Rails, Python, Eclipse, C, and C++.Top 14 Digg.com Programming Posts for the Previous MonthTop 12 Ruby on Rails TutorialsA former student asked me a few days ago how I learned Ruby on Rails. The answer was that I simply read alot of great tutorials. So in the spirit of sharing, here are the 12 tutorials that I found most useful: More… 23 commentsA MySQL Cheat Sheet”The MySQL cheat sheet is designed to act as a reminder and reference sheet, listing useful information about MySQL. It includes a list of the available functions in MySQL, as well as data types. It also includes a list of MySQL functions available in PHP, and a list of useful sample queries to select data from a database.” More… 31 comments Are You a Programmer? Myers-Briggs Personality Type TestA variation on the Myers-Briggs MBTI test, designed for programmers. Self-scoring, with lots of detail on each of the 16 types. Takes 10 minutes or less to take. More… 330 comments6 ways to make PHP Scripts lightning fast!6 things you can try to make your php scripts fast! More… 58 comments Crossing borders: Ajax on RailsThe hype for Ajax, a technique for making Web pages more interactive, is in overdrive. The Ruby on Rails framework is also flourishing, partly on the strength of its excellent Ajax integration. Find out what makes Ajax on Rails such a powerful combination. More… 26 commentsDiscover the Ajax Toolkit Framework for EclipseThe Ajax Toolkit Framework (ATF) is a core piece of the new Open Ajax initiative, which aims to increase accessibility to the powerful Web programming technique through the Eclipse Foundation. The ATF extends the Eclipse Web Tools Platform (WTP) by adding an Asynchronous JavaScript and XML (Ajax) development environment. More… 9 commentsPython Tutorial Index PagePython is a dynamic object-oriented programming language that runs on Windows, Linux/Unix, Mac OS X, Palm Handhelds, and Nokia mobile phones. More… 38 commentsAJAX Tutorials - A comprehensive List (over 130 listings)A comprehensive list (over 130) of tutorials on AJAX, JavaScript and other web development topics. More… 31 commentsDatabase-enabled AJAX with PHP…In this article you’ll learn how to create database-enabled Ajax requests using PHP and MySQL. We begin by creating the front-end HTML and JavaScript files used to make requests to the server-side. The requested server-side is a PHP file which bridges the gap between Ajax and a PHP object that connects to a MySQL database and returns results as an More… 49 commentsTop 20 Programming LanguagesThe index is not about the best programming language or the language in which most lines of code have been written. It can be used to make sure your skills are up to date, or what language your company should use when developing a product or service. More… 165 commentsThe Mother of All Computer Science Cheet Sheets!For all of us working towards our finals. This may be the last cheat sheet you will ever need. More… 150 commentsTeach Yourself C in 24 HoursWritten in a plain and clear format, this book is designed to help you learn the C programming language as quickly as possible. More… 93 commentsTeach Yourself C++ in 21 DaysLearn the basics of C++ in 21 days! Great guide for beginners. Remember, this is just an overview, fully mastering any program languages takes many years. But this is the guide to get you started! More… 60 comments1043 programming exercisesNeed to sharpen your skills, or perhaps that shiny new python/ruby/c++/java book didn’t come with any programming exercises? You can’t learn a new language by simply reading about it. Here you will find over 1,000 exercises ranging from easy to hard. Have fun! More… 52 commentsTechnorati Tags: ajax, rails, ruby, python, php, mysql, c++Popularity: 1%Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages. […]
great list of tips, thank you!
[…] Взято здесь […]
[…] Jaslabs: High performance php » Fast PHP […]
Sam - I wrote a template engine that processes its templates and saves them as PHP, simply using that code to generate the display. It keeps the content and display logic completely seperate, yet keeps everything in PHP. The overhead is as close to nil as you can get while still using a templating system. As for learning a new language - templating is not about complicated control structures - that’s what the language you’re writing in is for. That should be kept as far away from the HTML as possible, as client-side developers work on that, and you don’t want to expose them to 5 lines of PHP, setting and using global variables, etc., when just one custom tag can use. If having to learn 6 different tags gets in the way of developing a project, maybe it’s time to get new developers
[…] http://www.whenpenguinsattack.com/2006/08/14/using-php-in-large-websites-redone/ […]
[…] Sources: moskalyuk.com, whenpenguinattacks, iBlog, phpLens, wikimedia, phpbench, php.net, php.net - migration, […]
[…] I saw this site. It’s pretty old but very it contains a lot of helpful tips in making your PHP fast. (Aside from giving you a link to the article, I have copy/pasted the article here). […]
[…] 5 methods for lightning fast php scripts August 23rd, 2006 an informative article on five different ways to make your PHP scripts lightning fast. read more | digg story Filed under: Tech | […]
[…] 5 methods for lightning fast php scripts August 29th, 2006 A great article on making your PHP scripts lightning fast! read more | digg story Filed under: Tech | […]
[…] Fast PHP? - Jaslabs: High performance Software The following methods can help improve scalability with php applications. (tags: PHP optimization performance programming howto tutorial web php5) […]
[…] Buscando información sobre cómo optimizar el motor de PHP, me he encontrado con una web como la nuestra: Una empresa llamada JasLabs cuyo site en internet es un weblog con artículos técnicos. En uno de ellos habla de qué hacer para que PHP vaya más rápido, en otro de las 5 mejores herramientas para PHP, y en otro más, de los 10 mejores Frameworks para PHP. « Entornos visuales para desarrollo de AJAX Ajax on Rails » […]
[…] » Fast PHP The following methods can help improve scalability with php applications. (tags: php optimization performance programming web scaling) Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages. […]
[…] read more | digg story […]
[…] read more | digg story […]
Great tips though I don’t 100% agree with the Templates System one - it’s a bit general.