Tag: Static

Caching data using static objects

One classic scenario of website speed issues relates to retrieving data from a database and often it is the same data being retrieved over and over again. For example storing some of your site settings in the database was originally a great idea as it meant your admin users could configure them through an admin, but now every request from your real users is doing a database call to look up this information.

A way to reduce these database calls is to create a static object that will keep hold of the information once its been retrieved. This could simply be an int or string or it could be something more complex like a List or Dictionary that we keep adding to.

Lets use an example where we are retrieving details of a room. The room can have multiple properties including Name, Capacity and Description. Or database contains multiple instances of rooms that is repeatedly requested.

Rather than accessing the database directly we can create a function that will first look up the value in a List object and if it is not found then revert to loading the information from the database. If the information was retrieved from a database then we also add it to the list for future use.

code for looking retrieving the data

As the List is a static object it will continue to hold the information of the rooms for the life of the application. Some things to watch out for however:

  • Static objects will be the same for all users, they are not related to a session
  • Static objects are accessible across all threads so you need to be aware that anything you change in the static object will be changing on all threads
  • When you return the object you wanted you will most likely be returning a reference to the existing object not just its value

With these things in mind, whenever you are updating the list (adding, removing etc) make sure you create necessary locks so that only 1 thread executes at a time. In the example this has been done when we check for the existence of the item and then go to load it. Without the lock it would be possible for 2 threads to do the check and then both go to load the values. If this were to happen we would end up with 2 instances of room in our list. Even worse if we were using a dictionary instead of a list the second instance would cause an exception when it tried to add it to the dictionary. With the lock the second thread will wait for the first to finish executing before it runs the code.