XDocument Attribute Performance Concerns
I have a loaded XDocument that I need to grab all the attributes that equal a certain value and is of a certain element efficiently. My current
IEnumerable<XElement> vm;
if (!cacher2.TryGetValue(name,out vm)) {
vm = project.D开发者_如何学JAVAescendants(XName.Get(name));
cacher2.Add(name, vm);
}
XElement[] abdl = (vm.Where(a => a.Attribute(attribute).Value == ab)).ToArray();
cacher2 is a Dictionary<string,IEnumerable<XElement>>
The ToArray is so I can evaluate the expression now. I don't think this causes any real speed concerns. The problem is the Where itself. I am searching through anywhere from 1k to 10k items.
Do you need to call .ToArray
? I'm unclear on why you can't just loop over adding to the dictionary (or call .ToDictionary
). However; have you profiled? If there is a bottleneck here, you might try dropping back to XmlReader
and treating it as a firehose:
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element
&& reader.GetAttribute("attribName") == attribValue)
{
/* do something interesting for fun and profit */
}
}
With your existing code, though, I would be very tempted to make it:
vm.Where(a => (string)a.Attribute(attribute) == ab)
The difference is that by not calling .Value
it should work even when the attribute isn't set. Of course if you demand that this attribute is always set then an exception may be acceptable in this case.
精彩评论