PHP Developer / Blog

February
29th, 2008

10 more tips to make your PHP application scream - Part 2 of N

Digg this article · Save to del.icio.us · Stumble it!

The previous article in this series talked about how to set PHP up so that it’s a lean mean processing machine. Now we get to make sure that our PHP code follows suit.

Also read part 1 of this article.

I’ll cover 10 lesser known PHP functions or methods that can help streamline your PHP code.


Casting variables is fast
PHP internally casts a variable when it’s value is set. This is why you generally don’t want to $age = ‘10′;. By doing so you’re explicitly telling PHP that $age is a string. There are still times when you will want to explicitly cast a variable after it’s already been set. PHP provides numerous functions to do this including strval, intval and floatval. There’s a faster way to do each of these.

// this is slower
if(intval($age) > 13)

// this is faster
if((int)$age) > 13)

More information about casting variables here.

Don’t be pushy with arrays
An easy way to append something to an array is to use array_push. There’s a slightly faster way to do this which doesn’t require a function call and doesn’t include a return value.

// this is slower
array_push($myArray, 'myValue);

// this is faster
$myArray[] = ‘myValue’;

Opening and reading files
PHP5 introduced the file_*_contents functions. Not only do these require less lines of code but they also handle all of the core logic internally as a single native PHP function. Traditionally, you would use fopen/fgets/fclose to do this using some sort of loop and incurring numerous function calls.

// this is slower
$fp = fopen('/path/to/file.txt','r');
while(!feof($fp))

// this is faster
file_get_contents('/path/to/file.txt');

Update: As Amit posted in the comments using get_file_contents is a bad idea for large files. Consider using the fopen/fgets/fclose method or readfile.

Strings as an array
A really handy feature of PHP strings is that you can treat it as an array of characters. This is faster than using substr. The two are not identical but can be interchanged for numerous scenarios.

// this is slower
substr($string, 3, 1);

// this is faster
$string[3]

Update: Kevin noted in the comments that using {}s are deprecated in PHP 6 and you can use []s instead.

Being single isn’t so bad
When defining a string PHP lets you use either double or single quotes. The primary difference is that PHP extrapolates variables from inside of double quotes. This means that if you don’t have variables inside your string then single quotes incurs a little less overhead. If you do have variables to inject into a string you can use concatenation or pass pieces to echo as parameters.

// this is slower
echo "Hello, my name is $name";

// this is faster
echo 'Hello, my name is ' . $name;

// this is fastest (using comma instead of period)
echo 'Hello, my name is ' , $name;

Using MySQL
You can use the mysqli extension which provides a faster interface to MySQL. It’s good to note that PHP5 introduced the PDO library which can be used as a wrapper to mysqli. This is slower than using mysqli directly but the benefits of using PDO should be considered.

// this is slower
mysql_query('SELECT id FROM table');

// this is faster
$mysqli->query('SELECT id FROM table');

Storing session in memory
If you use PHP’s native sessions then it’s an easy change to switch from the slower file based session storage to storing sessions in memcache. You’ll need to set a few php.ini configurations including session.save_handler and session.save_path. Of course you’ll need to have a running instance of memcache. No additional changes need to be made in your code.
Checking the beginning of a string
If you need to check the first 5 characters of a string then a regular expression could do the trick. But of course there’s another faster way to do it using strncmp. The benefit is that it doesn’t require using the regular expression engine - an expensive cost for such simple checks.

// this is slower
preg_match('/^abcde/', $string);

// this is faster
strncmp('abcde', $string);

Put the most likely first
When writing conditional statements which have multiple expressions it’s a good idea to always place the most likely expression first. This will vary on whether you’re using || or &&.

// this is slower
if(false || true)

// this is faster
if(true || false)

The first shall be fast
When incrementing a numeric variable it’s common to use the post-increment operator by doing $var++. If possible you can use the faster pre-increment operator by doing ++$var. It’s important to know the difference so you can write your code accordingly.

Conclusion
These are just a few tips and while none of them alone will make your PHP applications blazing fast they don’t hurt. It’s a good habit to write good code from the start since it doesn’t cost any extra time. By all means don’t go back and rewrite existing code to implement minor performance tweaks.

Resources

As always…comments welcome!

11 Responses to “10 more tips to make your PHP application scream - Part 2 of N”

  1. Amir Says:

    Hi Jaisen,

    Some good tips there …

    There’s one caveat regarding file_get_contents(). You shouldn’t use it for large files because it puts the whole thing in memory as a string.

    fopen is much more efficient for buffering files gradually (particularly if you’re buffering contents out to screen or to file or something)

    e.g.
    $fp= fopen(’filename.doc’,'r’);
    while(!feof($fp))
    {
    echo fgets($fp,4096);
    flush();
    }

    You might want this behaviour in a document management engine …

    Only 4k of ram will be populated at a time, rather than the full size of the file (megabytes or whatever).

    A

  2. Kevin Says:

    I’d like to see some actual benchmark tests you’ve run with results graphed accordingly to show just how much faster each tweak is and when it is beneficial to use it and not really worth it.

  3. Kevin Says:

    Another thing to note is that you have to use the double quote if you want to use an escape sequence, such as \n. You can still have your performance gain by mixing quotes: ‘Hello, my name is ‘ . $name . “\n”

  4. Kevin Says:

    Using {} to access a string as an array is deprecated as of PHP 6. Since it is an array it makes more sense to use the [] anyway. $string[3]

  5. jaisen Says:

    @Amit, Thanks for the note. I made an update to the post noting what you said.

  6. jaisen Says:

    @Kevin, Good point. I added a note about that and changed my example.

  7. Chad Says:

    I wrote a benchmarking script, the results are extremely negligible for most purposes.

    It’s on my blog..
    http://conductr.com/

  8. jaisen Says:

    @Chad, Thanks for writing the benchmarking script. I’ve updated the post to include them in the “resources”.

    I agree with you that the performance gains are slight. While it’s rare that site will see the benefit of this it’s good to write code knowing what PHP is doing under the hood. Minimizing function calls, bypassing the regular expression engine and ordering conditional statements is just good programming practice.

    It would be a waste of time to refactor an entire application using these principles. There’s almost always more bang for your buck elsewhere. Generally at the database…which will be it’s own part in this series.

    It’s important to remember that PHP alone doesn’t make a site fast or scale..it’s a combination of several things — which is what I hope to touch on in this series.

  9. Chad Says:

    I totally agree that these tips are best practices if not great performance boosters.

    However, to me it’s more about going forward with a uniform practice that increases readability, performance, and reduces the need for refactoring.

    I don’t see going backwards for these gains. Let’s take wordpress, which has some pretty ugly source code and refactor it. That would take several man-hour days just to read through all of the source code, plus fixing the code. In the end, you maybe save a few tenths/hundredths of a second and you would have been better off investing your money (since time=money) in another server, bigger VPS, etc.

    It’s kind of the Rails mantra, keep throwing machines at the problem until it become worth your time to fix. Most applications never need this scale, but it’s good practice to use going forward.

  10. Chad Says:

    Oh, well I just read your front page and see you develop for Yahoo! I guess your apps are guaranteed to need scale, which changes things substantially.

    But for the average joe, like me, don’t worry about scale until you need to. Chances are your won’t.

  11. jaisen Says:

    @Chad - You bring up a good point. I hadn’t thought about including an article in the series which talks about writing easy to read/maintainable code - which in some cases conflicts with some of these suggestions. For a PHP application to scale it needs to be easy to follow the code for current and new developers. That’s often overlooked and time IS money - I’ll work that into the series.

    I should add a note to the beginning of each article which explicitly states to not blindly follow any tips mentioned below - but rather assess the pros and cons of each and implement accordingly.

    Additionally, I’m a huge proponent of Agile development and not over engineering early in the development process. Generally…bottlenecks are best addressed once they begin to creep up. With easily managed code addressing them should be quick.

Leave a Reply

Captcha
Enter the letters you see above.


About this site:
This is my (Jaisen Mathai) personal site for potential employers who want to see my resume or portfolio. My ideal job would be to work as a PHP developer on a large scale consumer website. My experience is in using PHP, MySQL, Ajax and JSON. I really enjoy creative brainstorming...taking a problem apart and narrowing 100 solutions down to the best one.

Thanks for stopping by. Be sure to drop me a line.