As ben, okplus and tom pointed out in comments to my Sorting a list of IP addresses in Python blog post, my sort function is very inefficient. As implemented, each IP address gets converted to decimal a number of times which is unnecessary and wasteful. Thinking about the bigger picture - using the function in an application - it doesn't make sense to convert the IP address to decimal in the sort function.
Since my goal was to extend the work of the iplib module, the solution, I think, should involve using this module more efficiently, if possible. The iplib module represents an IPv4 address using its IPv4Address class. When initializing an instance of this class, the address gets converted to decimal and stored in the _ip_dec attribute, accessible by calling its get_dec() method. So by converting the raw IP addresses to IPv4Address instances outside the sort function (which I would probably be doing anyway) and using the get_dec() method in the function should improve things.
So, here is what I hope is a more efficient sorting function:
Of course, comments are welcome.
Thanks to ben, okplus and tom for their helpful comments to my previous attempt.
Since my goal was to extend the work of the iplib module, the solution, I think, should involve using this module more efficiently, if possible. The iplib module represents an IPv4 address using its IPv4Address class. When initializing an instance of this class, the address gets converted to decimal and stored in the _ip_dec attribute, accessible by calling its get_dec() method. So by converting the raw IP addresses to IPv4Address instances outside the sort function (which I would probably be doing anyway) and using the get_dec() method in the function should improve things.
So, here is what I hope is a more efficient sorting function:
#!/usr/bin/python
import iplib
ips = []
for ip in ["192.168.100.56", "192.168.0.3", "192.0.0.192", "8.0.0.255"]:
ips.append(iplib.IPv4Address(ip))
def ip_compare(x, y):
return cmp(x.get_dec(), y.get_dec())
ips.sort(ip_compare)
print [ip.address for ip in ips]
Of course, comments are welcome.
Thanks to ben, okplus and tom for their helpful comments to my previous attempt.
Comments