luca
luca

Reputation: 37136

PHP performance and redundancy

I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

$comments=new Comment();
$comments->getComments();
echo count($comments);

Or I'm better build another function (apart from 'getComments')like :

function countComments($postid)
{
  //count comments per post
}

thanks

Luca

Upvotes: 2

Views: 472

Answers (3)

Tomáš Fejfar
Tomáš Fejfar

Reputation: 11217

See my answer in other thread: Zend_Db: How to get the number of rows from a table?

Upvotes: 1

Zoran Zaric
Zoran Zaric

Reputation: 1221

Counting your comments in the database is more efficient, because

  1. Only the count is transferred, so you save bandwidth between your database and the php process.
  2. You save IO because the result isn't generated and the data isn't read from disk
  3. A RDBMS is optimized for such functions.

Assuming, that you use Zend_Db something like this should work:

$query = $db->select()->from('comments', 'count(*)');
$count = $db->fetchOne($query);

Code redundancy isn't a problem IMHO here, it's just one or two lines.

Upvotes: 7

Sebastian Schmidt
Sebastian Schmidt

Reputation: 1078

I always would prefer to use a separate function which uses MySQL to count the posts. Because if you just need the count you would not have to request the whole rowset, which increases performance and saves resources.

Upvotes: 3

Related Questions