I have a small assignment to read IP addresses and from a bunch of external text files identify which country the IP address comes from. I opted to use XmlReader
and read the ranges from an XML file but unfortunately the performance has been quite abysmal (an average search time of around 7000 milliseconds).
Obviously serializing the ranges isn't an option as we're talking about 142,222 entries. Is there anything I can do to optimize my method or is there a quicker way to search this, without resorting to SQL?
class IPRangeRepository : IDisposable
{
public IPRangeRepository(string fileName)
{
this.fileName = fileName;
xmlReader = XmlReader.Create(fileName);
}
private XmlReader xmlReader;
private string fileName;
public string GetIPCountry(IPAddress adress)
{
while (xmlReader.Read())
{
// Ok instantiate object and then do comparison...
if (xmlReader.Name == "IPRange") {
var ipRange = IPRange.TryParse(xmlReader["Value"]);
if (ipRange.IsIPAddressInRange(adress)) return xmlReader["Country"];
}
}
//Return empty string if we don't find anything
return string.Empty;
}
public void Dispose()
{
xmlReader.Dispose();
}
}
IsIPAddressInRange()
an extension method ? – Heslacher Oct 8 '14 at 15:17