Is reading app.config expensive?

前端 未结 5 1798
青春惊慌失措
青春惊慌失措 2020-12-14 07:15

No question I am yet to be hit by any read speed bottleneck. I am asking to know; if reading app.config frequently is a bad programming choice. I have known of database oper

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 07:48

    Anything that ends up with disk IO is expensive (definitely when talking about rotating media).

    See What are the numbers that every computer engineer should know, according to Jeff Dean? on Quora to see the differences in speed.

    If you are reading a file repeatedly, you should cache the results (in particular if the file does not change).

    When using the default configuration, the .config file only ever gets read one time, at application startup and the results are cached in memory.


    Update, example as requested:

    private Configuration appConfig;
    
    private Configuration GetConfig()
    {
        if (appConfig != null)
            return appConfig;
    
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = GetConfigFilePath();
        appConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    
        return appConfig;
    }
    

    Assuming this lives in a class that has the lifetime of the application, you have now cached the configuration in memory for the lifetime of the application.

提交回复
热议问题