6

I have several SELECT statements on a PHP page, and I used Dreamweaver to generate those.

After going through the code it generated, there seemed to be alot of fluff which I could cut out under most circumstances, a mysql_num_rows() line for each statement being an example.

So I'm wondering if anyone can tell me whether or not this actually saves resources - considering the query is being run regardless, is there any actual overhead for this?


UPDATE: After following Chriszuma's suggestion about microtime, here are my results:

//time before running the query
1: 0.46837500 1316102620

//time after the query ran
2: 0.53913800 1316102620

//time before calling mysql_num_rows()
3: 0.53914200 1316102620

//time after mysql_num_rows()
4: 0.53914500 1316102620 

So not much overhead at all, it seems

totallyNotLizards
  • 8,489
  • 9
  • 51
  • 85
  • There is always overhead on a function call in PHP, but it is usually minimal, unless your calling it hundreds of thousands of times... – DaveRandom Sep 15 '11 at 16:04

2 Answers2

4

mysql_num_rows() counts rows after they have been fetched. It's like you fetched all rows and stored them in a PHP array, and then ran count($array). But mysql_num_rows() is implemented in C within the MySQL client library, so it should be a bit more efficient than the equivalent PHP code.

Note that in order for mysql_num_rows() to work, you do have to have the complete result of your query in PHP's memory space. So there is overhead in the sense that a query result set could be large, and take up a lot of memory.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • 1
    +1 That's why `mysql_num_rows` won't work when you use [mysql_unbuffered_query](http://php.net/manual/en/function.mysql-unbuffered-query.php) – webbiedave Sep 15 '11 at 16:13
3

I would expect that such a call would have an extremely minimal impact on performance. It is just counting the rows of its internally-stored query result. The SQL query itself is going to take the vast majority of processing time.

If you want to know for sure, you can execute microtime() before and after the call to see exactly how long it is taking.

$startTime = microtime(true);
mysql_num_rows();
$time = microtime(true) - $startTime;
echo("mysql_num_rows() execution: $time seconds\n");

My suspicion is that you will see something in the microseconds range.

Chriszuma
  • 4,464
  • 22
  • 19