php

Blog Archive

February 16, 2010

Speed tip # 1- Globalize your connections

When building a website one always hopes for success. A successful website earns attention and will give you positive credit. However, the more users your website attracts, the faster your code needs to be.

There are several ways of optimizing code and tools to assist finding bottle necks in your site. However, the best optimization is done at design level and not at code level. This indicates that you should design your site to be fast. Fast code on a poorly designed site will result in a slow site.

A database driven website where page fragments fire queries against the database must open a connection to the database and close it again when done reading. However, it's a bad design to open and close the connection several times over the webpage.

$mysql_link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password') or die("Error opening mysql connection");
$rs = mysql_query("select * from table where id>10 order by id asc", $mysql_link);
while ($row = mysql_fetch_array($rs))
{
print_r($row);
}
mysql_close($mysql_link);
...
$mysql_link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password') or die("Error opening mysql connection");
$rs = mysql_query("select count(id) from table", $mysql_link);
list($count) = mysql_fetch_array($rs);
echo "Found $count entities";
mysql_close($mysql_link);
The above snippet is obviously bad code. Look at the number of duplicated code lines. However, if you run a larger site where pages are generated by including various script snippets the running result might end up as above. Just look at the sample below:

include 'template.php';
include 'page_front.php';
include 'page_news.php';
echo template_header();
echo page_front();
echo page_news();
echo template_footer();

There is absolutely no way of knowing what the underlying pages does to retrieve data from the database. A faster design would be to open the connection once and close it when the page is rendered. Here is a brief example:
$mysql_link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password') or die("Error opening mysql connection");
include 'template.php';
include 'page_front.php';
include 'page_news.php';
echo template_header($mysql_link);
echo page_front($mysql_link);
echo page_news($mysql_link);
echo template_footer($mysql_link);
mysql_close($mysql_link);
As can be seen from above, the design visualizes where the database connection is used and the responsibility of opening and closing the connection is left to the caller of each function.