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
instanceofis 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
instanceofand 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 workload1.1 – Once you have done that, it should be a simple matter to run / rerun your benchmark with two or more versions of the IPv4 vs IPv6 test and measure which is faster.