HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Optimizing the reading of web.config

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readingtheconfigoptimizingweb

Problem

Here's the issue. When I build an asp.net application I create a singleton to read the values from the web.config file so that the values are only read once and gives a slight speed increase to the app. I basically do the following :

/// 
/// Static class that handles the web.config reading.
/// 
public class SiteGlobal
{
    /// 
    /// Property that pulls the connectionstring value.
    ///              
    public static string ConnectionString { get; protected set;}

    /// 
    /// Property that pulls the directory configuration value.
    /// 
    public static string Directory { get; protected set; }

    /// 
    /// Static contructor for the SiteGlobal class.
    /// 
    static SiteGlobal() {
        ConnectionString = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
        Directory = WebConfigurationManager.AppSettings["Directory"];

    }
}


Which I don't consider a bad optimization. (Suggestions for improvement are appreciated through.)

Now though I'm trying to read from a ConfigurationSection that can contain multiple area's for example :


    
                    
    
    
        
    


Where I can have multiple area's underneath ApplicationArea, such as test1 and test 2 above. The best I've been able to come up with for an optimization of this though is this :

public static string ApplicationArea(string skey, string skey2)
    {
        NameValueCollection nvc = WebConfigurationManager.GetSection("ApplicationArea/" + skey) as NameValueCollection;
        return nvc[skey2];                        
    }


Which is not saving the data and rereads the web.config file every time it's accessed. Is there an easy way to optimize the reading of the sections?

Solution

The web.config is loaded into memory once per-request anyway - it isn't loaded and parsed every time you access a section via the WebConfigurationManager. What speed increases have you actually noticed?

In fact, it might not even occur for each request, according to MSDN: 'These settings are calculated once and then cached across subsequent requests. ASP.NET automatically watches for file changes and re-computes the cache when any of the configuration files change within that file's hierarchy. When the server receives a request for a particular URL, ASP.NET uses the hierarchy of configuration settings in the cache to find the requested resource.' So, you're just doubling up on memory consumption; and I'm not convinced it's faster.

Context

StackExchange Code Review Q#2237, answer score: 8

Revisions (0)

No revisions yet.