Question

Say I have some 10 "categories" that I need to reference in a web app. Currently I'm storing these categories in the DB and am retrieving them (category name and id) during pageload in my basepage, storing them in a hashtable and then using the hashtable to reference the categories. I realized that the DB call is being made during each pageload. I only need to pull these categories once as they never change during a given session. What's the best way to do this?

  1. Do whatever I am doing, but store it as a Application variable?

  2. Hard code the categories in the code, and do away with the database?

  3. Store the categories in a session variable? And call the DB only if the session is empty?

  4. Or something else?

I'm just curious to know what the best-practice is for doing such things.

Was it helpful?

Solution

If the categories are user dependent then I'd store them in the Session variable; otherwise I'd use the ASP.NET Caching functionality (or preferred distributed caching). This allows you to avoid hitting the database whilst being able to control how long the categories should be cached for.

OTHER TIPS

Calling the database is not always as expensive as it seems, a typical website makes dozens of calls to the DB on each pageload. But if it becomes troublesome in terms of performance, consider using an ORM solution. The excellent open source NHibernate comes to mind, which is the "de facto" standard for mapping databases to classes and objects. Beyond the mapping, it automatically provides two levels of caching and connection pooling. Without too much trouble, your website outperforms any other's by a landslide.

The downside of using an ORM? To many people, it is considered a rather steep learning curve. If you want to read into this, make sure to pay a visit to the NHibernate Best Practices. A tough read at first, but definitely worthwhile.

If you combine NHibernate with FluentNHibernate, it becomes a breeze to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top