jsakamoto / ipaddressrange

.NET Class Library for range of IP address, both IPv4 and IPv6.
Mozilla Public License 2.0
370 stars 71 forks source link

Getting string[] from IPAddressRange #26

Closed AndreMantas closed 7 years ago

AndreMantas commented 7 years ago

Any better way of doing this?

private string[] GetIPsFromRange(string ipFrom, string ipTo)
{
    var range = new IPAddressRange(IPAddress.Parse(ipFrom), IPAddress.Parse(ipTo));
    var result = new List<string>(255); // could use range.Count here...
    foreach (var ip in range)
    {
        result.Add(ip.ToString());
    }
    return result.ToArray();
}
jsakamoto commented 7 years ago

I prefer this style:

using System.Linq;

private string[] GetIPsFromRange(string ipFrom, string ipTo)
{
    return IPAddressRange.Parse($"{ipFrom} - {ipTo}")
        .Select(ip => ip.ToString())
        .ToArray();
}
AndreMantas commented 7 years ago

Thanks, seems cleaner.

Is IPAddressRange.Parse($"{ipFrom} - {ipTo}") faster than new IPAddressRange(ipFrom, ipTo) ?

jsakamoto commented 7 years ago

I wrote benchmark app. ( code is here.)

image

Condition: Parse 20,000 items x 100 times.
Type 1: Avg.29.12 msec / Min.21 msec / Max.63 msec
Type 2: Avg.164.78 msec / Min.145 msec / Max.296 msec

Type1 seems to be 5~6 times faster than Type2.

Because Type2 (IPAddressRange.Parse($"{ipFrom} - {ipTo}")) is paid for re-formatting and syntax detection ("0.0.0.0-0.0.0.255" style or "0.0.0.0/24" style?) costs.

But please remember that elapsed mill seconds is about parsing 20,000 items, and it took only around 160 msec even Type2.

AndreMantas commented 7 years ago

That was my initial guess as well. Parsing the '{ipFrom} - {ipTo}' should always cause some overhead than receiving the ips in separate variables.

This is really helpful as I'll use this in something that must make as much operations per second as possible, thanks.