5

I need to determine if an InetSocketAddress is IPv6 or IPv4 efficiently. The only two ways I can see of doing this are either using the instanceof operator, or checking the length of getAddress() (which should return a byte[]). Both of these are less than ideal (instanceof is slow, and getAddress would have to make a copy of the array).

Is there a better alternative?

p.s.w.g
  • 141,205
  • 29
  • 278
  • 318
jon
  • 283
  • 4
  • 12
  • 3
    According [this](http://stackoverflow.com/questions/103564/the-performance-impact-of-using-instanceof-in-java), `instanceof` may not be as slow as you think. Personally, unless you've profiled your app and it's reporting instanceof as taking > 5% of your run time, then I would put off optimizing away `instanceof` for later. – Alistair A. Israel Aug 15 '11 at 03:10

4 Answers4

4

A faster solution is to compare types. The types Inet4Address and Inet6Address are final, therefore they cannot be subclassed.

Inet4Address.class == IPtoCheck.getClass();
Inet6Address.class == IPtoCheck.getClass();

Testing shows that this is more than twice as fast as instanceof and isn't affected by the type being compared, whereas the performance of instanceof on Inet4 and Inet6 addresses is different.

Curtis
  • 41
  • 1
4

I don't think that you will find anything faster than instanceof. In this particular case, I'd expect the JIT compiler to optimize it to loading and comparing a pair of pointers; i.e. roughly 5 machine instructions.

But even if instanceof is significantly slower than I understand it to be, it is highly unlikely that it will have a significant impact on your application's overall performance.

I suggest that you just use instanceof and only bother to optimize it if you have hard evidence of a bottleneck at this point; e.g. evidence from profiling your application on a realistic workload.

Stephen C
  • 669,072
  • 92
  • 771
  • 1,162
1

If you don't like instanceof, you could try:

Inet4Address.class.isAssignableFrom(IPtoCheck);
Inet6Address.class.isAssignableFrom(IPtoCheck);

I don't think there is a faster solution than instanceof or the above.

Jérôme Verstrynge
  • 55,046
  • 88
  • 271
  • 437
  • 1
    That will be slower that `instanceof`. The JIT compiler isn't able to optimize reflective type checking. – Stephen C Aug 15 '11 at 03:30
1

Compared to the overhead of constructing the InetAddress itself with its implicit DNS overheads the overheads if any of instanceof are trivial.

user207421
  • 298,294
  • 41
  • 291
  • 462