Always define a local variable [TotD]

Posted by hts | January 7, 2008 .

Pursuing to achieve the name of “the easiest to learn and use programming language”, PHP indeed makes your life easier by doing some thing for you. For example, you do not have to declare / define each variable you’ll use in your script - PHP creates them on-the-fly. While this speeds up the development of a script (somewhat), you should know that…

Problem

Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

Solution

The solution is obvious: just define the variables you are going to use as counters (when iterating arrays, for example).

Quick one for today, sorry bout this guys. I have some sort of semestrial exam at the end of this week, and I have to study a bit and catch up with other :). I’ll still write here, but at a lower rate. Thanks for reading.

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

4 Comments so far
  1. Dave January 8, 2008 11:04 pm

    I suspect the reason for the slowdown is that incrementing an uninitialised variable raises an error which needs to be handled and logged. Writing the error message out onto the disk will be much much slower than not having to do that.

    A good tip for the future: always check the phperror.log on your production server. Find the most frequent bug and squash it.

  2. hts January 9, 2008 1:26 pm

    Thanks for your tip, Dave. Sounds like a good thing to do.

  3. Wunar January 13, 2008 8:14 am

    Dave’s right, unknown variable raises a notice which needs to be processed, and it’s quite expensive. To be on the safe side, just learn good style, by using something like,

    error_reporting(E_ALL);
    ini_set(’display_errors’, ‘on’);

    and make sure there’s not a single notice/warning. the cleaner the error.log will be, the more you’ll be able to spot real errors.

  4. Dave January 26, 2008 11:10 am

    I’m torn between taking the hard line and displaying errors in the browser to force you to fix ALL of your errors and logging errors to disk so as not to accidentally leak sensitive information that could be used by a hacker.

    I’m a security auditor which is why I care about that stuff. PHP has a nasty habit of including sensitive information like absolute installation paths and SQL errors in it’s error messages.

    I’m also a sysadmin and I have put together a couple of scripts that aggregate all the phperror.log files from across all of our production servers and list them all in order of how often they occur. This list is generated every night and published on our intranet and there’s a bounty available (bottle of wine) for the developer that squashes the most requested bugs each week.
    I have also started doing the same thing with our MySQL slow logs because I think we SHOULD consider a 10 second query to be a bug in the same way that a PHP fatal error is.