Ryan Jones Blog – dotCULT.com Ryan Jones Blogs About Internet Culture, Marketing, SEO, & Social Media

August 31, 2006

Code Optimization Tips Part 1

Filed under: Uncategorized — Ryan Jones @ 12:00 am

I realized for being a software engineer that I haven’t written much about programming or coding or anything else. I work mostly with PHP and MySQL, but as some of our applications are getting mad traffic now, I’ve been doing every little thing possible to optimize them.

Here’s a few code optimization tips (mostly PHP) that may not seem obvious to everyone:

  • $i++ vs ++$i Remeber back in college? There was always some sort of ++i / i++ trick question on exams right? So what’s the main difference? Most of you have been hard coded to use $i++ everytime, however that’s not always the best idea. The post increment (i++) actualy creates a temporary variable in memory to retain the value of i before incrementing. The pre increment (++i) doesn’t do that. It simply increments i. If you want to use the incremented version of i inside your loop only, then you might as well use the pre; it’ll save you a bit of memory.
  • using sizeof() or .size() or whatever. How many times have you done this?

    for(i=0; i < sizeof(array); i++) {

    While this is technically correct, it isn’t the best solution when the cardinality of array is large. Coding it this way will actually re-calculate the size of the array every time the loop runs; and the functional overhead can get expensive. If possible, you should calculate the size once then compare against that.

  • Speaking of functional overhead…Don’t use functions where built in operators will do. For example, this code:

    if (strlen($foo) < 5) {

    can be done without all the overhead by using some of php's natural operations like this:

    if(!isset($foo[4])) {

    The difference here is that isset() is built in to the language (it works like + or -) whereas strlen isn't. (it works like a function you define)

Anyway.. that's enough for now. I'm taking a vacation this weekend.. but when I get back, I'll post some other cool things you might not have known.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress