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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With