MWard
MWard

Reputation: 135

Processing data sent and received by a socket server in c#

Hey everyone. This place is like a goldmine of knowledge and it's helping me so much! My next query is:

I have byte data being sent to my c# socket server. I am converting it to an ascii string, then splitting the data based on a common character (like the bar | character) and using the data. Typically the first piece of data is a command as a 4 digit number. I can imagine this not being very efficient! What would be the best way to process the data is an receiving, efficiently?

Related, how I be trapping and processing commands? Multiple if statements or a large case/switch statement. I really need speed and efficiency.

Upvotes: 0

Views: 311

Answers (2)

Alessandro Vermeulen
Alessandro Vermeulen

Reputation: 1331

If you really need the performance I guess you shouldn't use a string representation for your command but work directly on the bytes. Four numbers in string format are 32 of 64 bits (depending on which charset you are using) in size, whilst a single byte is sufficient to store a four digit number. Using a lot of branches (which if-statements are) also effects your performance.

My suggestion is that you reserve a fixed size prefix in your message for the command. You then use these bytes to lookup in O(1) in a table which command you should execute, this table can be filled with object that have a method execute. So you can do something table[command].execute().

That being said, I don't think the performance-gain would be that large and that you are better off (maintenance-wise) by using one of the serialization libraries out there.

Upvotes: 0

jgauffin
jgauffin

Reputation: 101130

Typically the first piece of data is a command as a 4 digit number. I can imagine this not being very efficient! What would be the best way to process the data is an receiving, efficiently?

No, converting a number to/from a string is not efficient. But the question is: Do it really matter? It sounds to me like you are trying to do premature optimizations. Do not do that. Your goal should be to write code that is easy to read and maintain. Do not do optimizations until someone actually complains about the performance.

Related, how I be trapping and processing commands? Multiple if statements or a large case/switch statement. I really need speed and efficiency.

Again. Determine that the command processing really is the bottle neck in your application.

The whole processing really depends on what you do with the incoming messages. You provide way to little information to give a proper answer. Create a new question (since two questions in one is not really allowed). Add code which shows your current handling and describe what you do not like about it.

Upvotes: 1

Related Questions