Can this code be made more performant, converting bytes to struct data

I have created an example code of a byte array, and im creating slices and converting slices to the field types in a struct.

The idea is i receive a TCP message as a byte array, the first index tells me the overall message length, then from that i slice up the byte data to add to my struct.

It works, but if i have thousands of connected TCP clients all sending messages, this obviously needs to be as performant as possible.

Here is the playground code: Go Playground - The Go Programming Language

I created a buffer and added some data. In this case the message reads as:

[0] = messageSize
[1…4] = userkey (uint32) //4bytes
[5…8] = userID (uint32) //4bytes
[9:messageSize] = username (string) //the remaining bytes

Can i improve this at all ?

First and foremost, avoid premature optimization. Are you sure this code will become a performance bottleneck in your app?

When you finish the app and run load tests, maybe you will find that it scales well for the expected workload, or maybe you will find that the bottlenecks are somewhere else.

Regarding your code, on a brief look I see no unnecessary allocations in Write(), so I guess there is little room for improvement. (Due to the natue of slices, slicing off a part from an existing slice or array does not allocate anything.)

1 Like