Edwin
Edwin

Reputation: 827

Counting vs Storing number of posts

So this is more of a general question. Here is the deal.

So I made a web application which needs to know how many posts the user made for an award system. The more post the more rewards you get.

The problem is, I don't know what would be a better solution.

  1. One solution is to store the number of posts in the database and just retrieve which is what I am leaning towards as it seems this would cause less # of accesses to the database.

  2. The other option would be to count the number of posts dynamically which is easy enough to do. However this would mean that I would have to recalculate the data every time a page is refreshed. Of course, you could be smart about this and make it so it only counts when a new post has been added, but it would require more work.

Now I don't have a problem with either solution. In fact, I have implemented both solutions before, however I was wondering if someone could tell me which is better OR if they have another solution to this.

Upvotes: 0

Views: 118

Answers (4)

Deckard
Deckard

Reputation: 2450

I would always go for your first option and store the number of posts for the reason you already gave and more:

If at some future point in time you intend to clean up the database of posts and purge old posts your users won't loose their current count. Also you will be flexible to enhance the reward system later by maybe giving points for 'better' posts, and less points for normal ones. You also will be able to manually adjust point data without having to hunt for their posts.

In addition you might not know how successful your board system will ever be. Maybe at some time in the future it might be taking too long to calculate the value on the fly.

Upvotes: 2

imm
imm

Reputation: 5919

Without knowing too much about your system, I think a solution combining both options might be something to try. Consider creating a cron job which generates these counts and stores them in a table. You would then refer to that table when looking up post counts. You wouldn't have the most up-to-date results immediately, but you might not need them to be.

Upvotes: 1

stan
stan

Reputation: 4995

This is a very subjective question. In general, counting up the posts each time would take longer, but for a small amount of posts, it could actually be worse. My advice would be to profile you application. Load up 10, 100, 500, 1000 posts in the database and try each approach. Then go from there. I'm sure caching will be involved here. Also look into APC caching, which you can use to store the number of posts you have and retrieve it later right from PHP.

Upvotes: 2

fjlj
fjlj

Reputation: 146

i would say that storing the number of posts on the user and incrementing it each time they post would cause less strain on your database and would take less load time for update and query than if you were going to count all the posts....

Upvotes: 2

Related Questions