Search code examples
c#xmlwpfpropertiesdesktop-application

What is better practice here when it's about to repeat same code multiple times?


I'm working on wpf application, and there is one part which should be repeated many times, acctually it's about printing documents, everytime when user clicks print it will be executed, so some informations like PrinterName, Paths etc I'm storing in XML file, and I'm wondering because that action will be repeated many times is it better to store it into a global variable, and set it only once (for example in App.xaml file in Application_Startup method) and use it any time I need, maybe it is faster than to read it everytime from my XML?

Here is an code example:

Solution with XML:

//call code below everytime user wants to print document
 Printer printer = new Printer();
 printer.AdressAnswer = Globals.ReadValueFromXML("answeraddress");
 //ReadValueFromXML is my method which is returning value from xml and is defined below




public static string ReadValueFromXML(string nodeName)
 {
    try
    {

     XPathDocument doc = new XPathDocument("C:\\ApplicationSettings.xml");
     XPathNavigator nav = doc.CreateNavigator();
     // Compile a standard XPath expression
     XPathExpression expr;
     expr = nav.Compile(@"/settings/" + nodeName);
     XPathNodeIterator iterator = nav.Select(expr);
     // Iterate on the node set
     while (iterator.MoveNext())
     {
        return iterator.Current.Value;
     }
     return string.Empty;
    }
    catch
    {
       //do some error logging here. Leaving for you to do 
       return string.Empty;
    }
}

Solution with global variables:

 Printer printer = new Printer();
 printer.AdressAnswer = Globals.PathToFolder;

And

 Globals.PathToFolder

would be previously set in

private void Application_Startup(object sender, StartupEventArgs e)
{
    try
    {
     //Call again ReadValueFromXML method but call it only once and use static variables multiple times 
     Globals.PathToFolder = Globals.ReadValueFromXML("answeraddress");
    }
}

And now I'm wondering which solution is better and why?


Solution

  • Of course it is (at least theoretically) faster not to read the XML values from the file each time. Whether this performance benefit really matters in practice is another question. You need to perform performance testing/measuring to find out.

    If the values won't change, you could read them once and store them in memory for the duration of the application's lifetime. It is a tradeoff between memory usage and the execution time of your method really.

    But you could for example call the ReadValueFromXML method once from a static constructor of the class in which the values are being read and store the valuess in some static class that you then use in your "real" print method.