3

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 ?

1
  • You could also consider creating handler class for each message type Commented Jun 19, 2015 at 13:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.