Search code examples
asp.netvb.netclasscachingshared

cache or shared class for global variables in aspnet


cache and shared classes are application wide. there are some details I know but here's scenario:

I'm keeping parameters in database. I read them to datatable and store them in cache. whenever I need I directcast cache variable to datatble, query it and get the result. So I'm not using sql server every time.

Alternative is: read database and store it in class shared variable Whenever needed I use this shared variable (datatable) and query it. if this variable is empty I fill ilt from db. as variable is datatable I cont need to directcast it.

which one is preferred ? OR can I use any of them as there's no difference.

This class is not a special one. Just contains functions that reads parameters from database. To speed it up I started to use aspnet cache but I noticed that I don't need to because class variables can handle that.

any suggestions ? Can you think any possible outcome for this scenario that only works with parameters that won't change ?

    class Class1

       private shared localVar as datatable

       public shared function readParam1 as string  -- this is my old method
          ... SELECT from params table
          return  value
       end function

       public shared function readParam2 as string   -- then I implemented this
          if httpcontext.cache variable is empty then
               ... SELECT from params table
               ... set cache variable
          end if
          value = directcast(cachevalue, string) 
          return  value
       end function  

       public shared function readParam3 as string  -- now I'm planing to use this
          if localVar is empty then
               ... SELECT from params table
               ... slocalVar = sql table
          end if
          value = select value with localVar.Select function 
          return  value
       end function 

end class  

Solution

  • Shared variables are the winner here: 1. they would be a little faster than cache because cache needs to lookup dictionary. 2. they are more readable, easier to use

    In fact I can't remember use for cache. Because whatever you store in cache is shared data, so? In fact I'm so curoious about this question I'll open new stackoverflow question: asp.net shared variables vs cache