ipinfo / rust

IPinfo Rust library for IPinfo API (IP geolocation and other types of IP data)
https://ipinfo.io
Apache License 2.0
56 stars 14 forks source link

Optimize `is_bogon` by 10-100x #50

Closed Alextopher closed 11 months ago

Alextopher commented 11 months ago

This PR improves the preformance of is_bogon by

  1. Avoiding a lot of duplicate work by pre-parsing IP networks in a lazy_static!.
  2. Treating IPv4 and IPv6 addresses seperately. A v4 address can never be part of a v6 subnet.

Some rough benchmarks puts this change at a >100x preformance improvement for is_bogon for ipv4 addresses.

I expiremented with using a radix tree. I found it preformed ~45% faster on random ipv6 addresses but ~33% worse on random ipv4 addresses. I don't think it's worth the additional complexity to use a trie, yet.

While making this change I thought it would also be valuable to add:

pub fn is_bogon_addr(ip_address: IpAddr) -> bool;

This allows users to avoid some memory allocations in some use cases. We might also find some uses within this library later.

# 10_000_000 random ipv4 addresses
new: 386.25305ms
old: 39.090128764s
Speedup: 101.203415

# 10_000_000 random ipv6 addresses
new: 4.575585554s
old: 48.682978251s
Speedup: 10.639727
Alextopher commented 11 months ago

This change should be semver minor change