PHP Best Practices in Performance – Part 2

Date: 16 Feb 2010 Comments: 0

After PHP best Practices in Performance Part 1, here’s the next post from the series:

1. You can use array_keys() within foreach() when dealing with arrays. The reson is that foreach returns a copy of the array value. Using of array_keys will avoid excessive memory consumption, ex.

foreach(array_keys($array) as $ak)
{
$v =& $array[$ak];

}

2. Not everything has to be written in OOP. Often OOP is too much overhead, because each method and object call consumes a lot of memory.

3. Instead of implementing every data structure as a class, you can use arrays instead.

4. Do not split methods too much. Before doing that you can think which part of your code you will really re-use.

5. If you don’t need some variable, you can unset it to free memory, especially large arrays, ex.

// declare some variable
$a = ‘DevTheWeb.NET is a nice site :)’;

// after you don’t need $a
// inset it to free memory
unset($a);

6. If some method can be static, you’d better declare it as a static.

7. When you increment an object property (ex. $this->counter++), that operation is 3 times slower than incrementing a local variable (ex. $counter++).

8. Do not use sprintf() for string concatenation, you can use use the concatenation operator (ex. $full = $str1.$str2.$str3;). The reason is that the concatenation operator 2 times faster than sprintf().

I hope, you’ve found something useful in the information above :)

Leave a Reply


Spam protection by WP Captcha-Free