Parse a smaller XML multiple times or a larger XML once using LINQ to XML
I am writing a process for an ASP.NET website which开发者_如何学编程 will look-up a certain value from an XML file and perform a redirect. I am using LINQ (C#) to parse this XML.
I have hit a decision point where I have to look-up alternate values within the same request. I have two solutions:
Look-up each value separately. This will mean parsing the XML twice. But the XML size will be much smaller
Store multiple values in the XML and parse XML once. This will make the XML larger.
So which approach will have less of a performance overhead considering this for a website with some concurrency?
Simply put should I parse 200 elements once OR 100 elements twice?
Neither. Cache the parsed result until it is changed (if ever).
Why not parse it into memory once and then do lookups in-memory? E.g. read it into a Dictionary<> on your Application object. Put a FilesystemWatcher on the file and re-parse if it changed.
My $0.02:
caching the XElement (and repeatedly query) that is good enough until your profiler tells you otherwise.
Ok, I fetched the results for both scenarios via my Linq query and then looped through the two XElements to determine which one I need to use. I just needed to think a bit more. So, now, I have a much smaller XML and a single look-up.
IEnumerable<XElement> mping = (from mpings in mpingXML.Elements("mping")
where mpings.Element("sptrn").Value.Equals(sourceURL, StringComparison.InvariantCultureIgnoreCase)
&& (mpings.Attribute("lcl").Value.Equals(locale, StringComparison.InvariantCultureIgnoreCase) || mpings.Attribute("lcl").Value.Equals("ALL", StringComparison.InvariantCultureIgnoreCase))
select mpings);
精彩评论