kreoton web development

Archive for February, 2008

XX ways to improve your PHP scripts execution time

Tuesday, February 12th, 2008

1. Many same kind of articles says that ‘require_once is expensive’. Ok we know that but what to do? Here is some ways how to include your php files not using ‘require_once’:

  • a) If you need to include object class file check if class not exists and then include:
  • <?php
    	if (!class_exists('testClass'))
    		require '../testClass.php';
    ?>
  • b) If you including simple script or template, define something in included file then check if it is not defined and then include it.
  • <?php
    //include.php
    define('INCLUDE', 1);
    #code ...
    ?>
    <?php
    //script where include file should be included
    if (!defined('INCLUDE'))
    	require 'include.php';
    ?>

2. If you can do not call functions in loop. Top programmers mistake is calling count() or sizeof() functions in for() loop. How to fix this you can find in every ‘XX ways to optimise your PHP code’ articles, but do not do like this:

<?php
	for ($i=0; $i<count($somearray); $i)
	{
		#code
	}
?>

You can fix this code like this:

<?php
	$counter = count($somearray);
	for ($i=0; $i<$counter; $i++)
	{
		#code
	}
?>

Or like this:

<?php
	for ($i=0, $counter = count($somearray); $i<$counter; $i++)
	{
		#code
	}
?>

Not only count() or sizeof() slows your code, I can say that every function called in loop slows yor script. Take a look at example bellow:

<?php
 
function build_home_path ()
{
	$sql = "SELECT value FROM settings WHERE key = 'path' LIMIT 1";
	$res = mysql_query($sql);
	$row = mysql_fetch_assoc($res);
	return $row['value'];
}
 
//build menu
$menu_items = array('home'=>'Home Page', 'about'=>'About Page');
foreach ($menu_items as $path => $title)
{
	echo '<li><a href="'.build_home_path().'/'.$path.'">'.$title.'</a></li>';
}
 
?>

How you see this code is absolutly good, and works fine, but can it be a little more faster? Yes it can be just look at build_home_path() function call. Function build_home_path() is called every loop interation, thats no good because it do just one thing it gets home path ( like http://www.kreoton.net/). Here is solution how to fix it:

<?php
//we can rewrite our loop contents in this way
$menu_items = array('home'=>'Home Page', 'about'=>'About Page');
$home_path = build_home_path();
foreach ($menu_items as $path => $title)
{
	echo '<li><a href="'.$home_path.$path.'">'.$title.'</a></li>';
}
?>

Thats all for this time come back for part 2.