I wonder if there is a big difference between those 2 functions, is one faster or more efficient than other ?!

function nb1($cat_id)
{
$query = "SELECT COUNT(site_id) FROM site_list WHERE cat_id = '$cat_id'";
$result = mysql_query($query);
return mysql_result($result, 0, 0);
}

function nb2($cat_id)
{
$query = "SELECT site_id FROM site_list WHERE cat_id = '$cat_id'";
$result = mysql_query($query);
return mysql_num_rows($result);
}

    If you just require the count, then use MySQL's count function. The reason is 'cause if you do a SELECT site_id query, the rows have to be passed from MySQL to PHP. That takes a little while longer than MySQL passing to PHP just a number for the count.

    Diego

      From programming point of view it might be easier to use mysql_num_rows() to determine the number of rows returned by a given query, but when speed and server load are important then you should definitely use the COUNT() function. Depending on the type of base you use (Inno, MyISAM, ISAM, Heap etc.) the COUNT() founction would be several times faster - first if your DB machine has enough memory for MySQL to load the base the query would be executed extremely fast, and second you are saving the transfer generated if you select all rows. Imagine that your DB server is on the North Pole and your application server is on the South Pole - you will definitely prefer to use COUNT() as it would save you both time and money. 🙂

      Regz

        Write a Reply...