When looking to optimize code you've been given, the only real way is to walk through it and understand well what the computer is doing. Then you can see any redundancies or major time hogs.
First, pay the most attention to the most inner loop, which is executed the most of all code, and "slow" operations, like file input/output.
Are you including functions or files that you aren't using?
Can you break up the page's functions into groups of functions in different include files so that, for example, you only include the functions/classes used for printing a customer's shopping cart when the customer is viewing the cart?
Are you taking into account if statement short circuiting? Example:
PHP Code:
foreach ($largearray as $element) {
if (eregi($one, $two) && $is_ok) {
do_something();
}
}
In this example, to get to do_something(), $is_ok must be true and the regular expression must match. It is neglegible whether or not $is_ok is true, but the call to eregi() can be computationally intensive. If the two expressions were reversed, the interpreter would check $is_ok first, and if it is false, there's no need to call eregi(), so the interpreter would skip it and the execution would run faster. The same can be applied to if ($is_ok || eregi($one, $two)): If $is_ok is true, there's no need to call eregi().
You can measure how much time different parts of the code take to execute:
PHP Code:
$start_time = microtime(true);
//The code you're measuring.
echo 'Code executed in ' . number_format(1000 * (microtime(true) - $start_time), 2) . ' ms.';
If you have some problematic code, you can post some of it and we can point out any issues we see.
Cheers!
Bookmarks