Archive

Archive for August, 2007

Increasing PHP performance | PHP optimization

August 9, 2007 preetul 1 comment

Conditions

The triple equals sign increases performance because PHP performs a strict check on the two variables.

 

 

<?php
if($variable1 === $variable2) {
//code
}
?>

Concatenation

I usually concat a string with the following:-

 

 

<?php
echo '<option>'.$variable.'</option>';
?>

But a better way is to use commas to output the string because PHP only has to output it instead of using concatenation.

 

 

<?php
echo '<option>',$variable,'</option>';
?>
 According to some PHP experts, the real fastest way for concatenated input is to use the implode() native PHP function.

Example :

 

 

echo implode(‘’, array(‘foo’, ‘fee’, ‘fum’);

Small coding chages  Matters: 

1. Use single quotes instead of double quotes for strings wherever possible. This saves the parser the overhead of searching for variables inside double quoted text.

2. Use ++$i instead of $i++. The second one uses a temporary copy of $i to add 1 to, then assign to $i.

3.

 

 

for ($i=0;$i<count($some_array);++$i) {
}

is slow

 

 

$temp=count($some_array);
for ($i=0;$i<$temp;++$i) {
}

is faster

 

 

for ($i=0;isset($some_array[$i]);++$i) {
}

is fastest

note: the for-loop that consider as the fastest has one major drawback: it only works, if the array is continuously numerated.

note 2: The better comparision would be for ($i=0;$i<count($array) && isset($array[$i]);++$i)

Of course count() should be pre-read first.

4. echo is faster than print because it is a language construct, not a function.

5. use include ‘/some/file.php’ instead of include(’/some/file.php’). Same for require and the _once equivalents.

6. Type cast instead of type convert (e.g use (int)$string instead of intval($string))

7. In case of mysql functions use either mysql_fetch_assoc() or mysql_fetch_row() but not mysql_fetch_array() because [probably] you won’t need both an index based array and an associative one too. Usually you will use either $array[$i] or $array[’key’].

I  found the  follong site  interesting:

http://webdevlogs.com/php-speed-freaks


Categories: General