XML parsing inside a loop
Performance ยท from work on a medical-insurance integration
A third-party integration I worked on was slow. For every item it processed, it parsed the same XML configuration again and fetched broad lists of data (doctors, drugs, pharmacies, states) when it only needed one record from each.
The fix was not a faster XML parser. I moved the parsing out of the loop, since its result never changed between items, and changed each fetch to ask only for the record the current item needed.
// before: parsed and fetched on every item foreach (var item in items) { var doc = XDocument.Parse(config); var all = repo.GetAll(); Apply(item, doc, all); } // after: parse once, fetch by key var doc = XDocument.Parse(config); foreach (var item in items) Apply(item, doc, repo.GetByKey(item.Key));
The general lesson: when a loop is slow, look first for work inside it that does not depend on the loop variable, and for queries that return far more than the loop uses.