Thus far, we have discussed only optimizations that pertain specifically to CPU usage. The topic of output optimization, however, pertains not only to CPU usage but to bandwidth usage as well.
For bandwidth usage, the rule is quite obvious: The more output you have, the more bandwidth you will use. This is bad in many respects, such as slower pages, higher costs, and so on. Although reducing the amount of output your scripts require depends largely on the application, a number of things can be done regardless of application to reduce the bandwidth requirements, such as:
Storing client-side code (JavaScript, style sheets) in a separate file that is included on every page.
Taking advantage of the properties of HTML tags to avoid unnecessarily duplicating attributes.
Removing all unnecessary whitespace from output.
Compressing output before sending it to the client.
Again, it may seem that some of these optimizations are trivial (such as the removal of whitespace). However, consider a site that receives 200,000 hits a month, which saves 300 bytes per hit by removing whitespace from its HTML documents. This simple optimization will save 60,000,000 bytes a month and 720,000,000 bytes a year in bandwidth. This improvement can be even more substantial by storing common cacheable things such as JavaScript code or style sheets in a separate file. More importantly, these simple optimizations tend also to equate to not only a faster, but a cheaper, website.
From a PHP perspective, documents can be optimized through the use of output buffering and the zlib compression filter. HTML documents can be compressed prior to being sent to the browser. Although this does put an additional strain on the CPU, for sites that have limited bandwidth, the trade-off may be reasonable. Depending on the document, upward of 80% of the normal bandwidth can be saved by compressing the document prior to sending it to the client.
Caching and PHP
Throughout computing, the technique of caching has proven itself as a viable method of increasing the efficiency of computer programs. In fact, not only has caching been a viable method, it has been an extremely effective one. Websites, by their very nature, lend themselves quite nicely to the caching model, which is effective only when multiple requests for the same information are made.
Consider a website that sells books for an example of how caching can improve performance. On this website is a complete catalogue of all the books that can be purchased, each on its own page with the details of the book in question. As you would expect, the basic implementation of this book catalogue is a script that executes the following operations:
Do any initialization, session management, etc.
Determine the book the user requested to view
Retrieve the relevant information about the book from the database