Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of performance in Java

I am working on a TCP server application. When a message is received, a new instance of an object representing this message is created. À function in the messages handler is then called and this new instance is passed as a parameter. This parameter is of type "IMessage" (interface for message). At that point, i need to identify the Message type.

My question is : in order to have the best performences, should i add à unique identifier in each IMessage instance, like an Int, or should i use instanceof ?

like image 325
Omen Avatar asked May 06 '26 05:05

Omen


2 Answers

You are basically asking if it is faster to test an integer field or use instanceof.

There are two answers:

  1. It depends on the actual code that you write, and the platform that you run it on. The only way to know for sure it to write the code (both versions) and then either benchmark them, or dump the native codes that the JIT compiler emits and analyse and compare them1.

  2. The answer most likely doesn't matter. The percentage of time spent in the if test in dispatching the message is likely to tiny compared with the rest of your application. (And if performance really matters this much to you, you should probably be implementing the server in C or C++.)


1 - The later requires deep understanding how assembly code performs. It is a difficult topic.

like image 51
Stephen C Avatar answered May 08 '26 16:05

Stephen C


I would suggest you have identifying id's in the for of a byte that you put in as first thing in the message. With this byte you identify the handling object which reads the arraybuffer into the object values.

The flow would be:

MessageSender: Create arraybuffer starting with identifying byte corresponding with message class. Give buffer to message class to write data to. receive buffer back put it on the network channel.

At the other side the first byte is read of the received arraybuffer. the byte identifies which class should process the message. The array buffer minus identifying byte is patched to the message handler which decodes the array buffer and triggers whatever needs to be triggered.

Thats how I'd do it.

like image 27
Tschallacka Avatar answered May 08 '26 16:05

Tschallacka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!