Home arrow PHP arrow Page 2 - Writing Clean and Efficient PHP Code

Loops & Other Conditionals - PHP

If you've ever had to go back to an application you wrote after an extended period of time, you already know the value of clean, well documented and efficient code. But how can you make your code better? Here are some tips that'll help you speed up and clean up your development cycle.

  1. Writing Clean and Efficient PHP Code
  2. Loops
  3. Objects
  4. Code Reusability
By: David Fells
Rating: starstarstarstarstar / 140
May 26, 2004

print this article



One way or another, all pseudo code is eventually converted to machine code. This code will occupy some finite amount of memory. Some languages, such as Java and the .NET Framework go through some extra steps for portability sake before producing machine code by generating IL (Intermediary Language) code. Although it is not always a point of concern, the machine code produced can vary wildly in size based on the pseudo code a developer produces. In PHP, there are a few key ways to minimize the amount of memory and machine code overhead generated by your application. In a small personal site this may not matter, but in a performance-critical situation, the savings here can be just as valuable as the savings earned by writing efficient database queries. The best place to start the discussion is with loops and conditional statements.

Case Statements - A case statement produces roughly 1/5th the amount of machine code as an if/else structure that completes the same task. Use case statements whenever possible! You can use a case statement when you are expecting an object to contain a particular value chosen from a range of known values. Case statements also allow you to provide a default fork for unknown values, which makes it possible to use a case statement in the majority of places where you may want to use an if/else statement. The difference in memory overhead between these two statements is fairly nominal, but the case statement is more efficient to some small degree.

Loops - Loops vary more drastically than conditionals due to the nature of the operations they perform. PHP offers a number of loops, including some higher level looping methods based on the each() function. When deciding what type of loop to use, consider the operations taking place. Let's look at the following example, where we have a query that will return roughly 1,500 results.

$r = mysql_query('SELECT * FROM someTable LIMIT 1500');
for ($i = 0; $i < mysql_num_rows($r); $i++) {
 print mysql_result($r, $i, 'ColA').mysql_result($r, $i, 'ColB');

while (($row = mysql_fetch_assoc($r)) !== false) {
 print $row['ColA'].$row['ColB'];

The first option requires simply one scalar variable used as a counter for iteration, using a lightweight access method to read buffered data from a result handle. The second example uses an array constructor function to build an array and evaluate it's contents on each iteration, and then references the array two times per iteration. Despite what you may guess, "OPTION 2" runs significantly faster. It has lower memory and machine code overhead. The examples are somewhat poor in that they demonstrate poorly written code; database access handled in-line with iteration, and output mixed in. Ignore that. The building blocks are what contribute to the overall overhead of the application, and understanding that will help you make the right choices for your application. You may find it easier to use an associative array in iterations than a result handle cursor, but in a proper app, you would be performing this operation at the object level, and output would be handled elsewhere, driven by object oriented iteration of the values that were loaded into an object from our query.

>>> More PHP Articles          >>> More By David Fells

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: