Umer
Umer

Reputation: 1921

C# socket receive buffer size cost

I am receiving some data over socket (with some start and end character). I can use a byte receiving mechanism that should receive one byte at a time, add it to some queue kind of thing and receive next until ending character found. Or i can make a chunk receiver and find an ending character to terminate my message...

My question is, what is cost of increasing / decreasing buffer size?? in my perception, decreasing buffer size should increase memory io but does increasing buffer verify that I'll be increasing IO performance as well?

Upvotes: 1

Views: 2077

Answers (1)

jgauffin
jgauffin

Reputation: 101150

Never re-size a buffer in a socket application. It might not matter for a socket application where there aren't that many simultaneous operations. But it's a bad habit that's easy to get used to.

Handling a buffer larger than the actual data isn't that hard to work with. Just check all Stream methods. They have a offset and count property which tells where you should start processing and how many bytes you can process. Same thing here.

And to answer your question: The cost is that .NET need to allocate a new memory "slot" and that the memory gets more fragmented for each request.

Simply allocate a 15kb buffer directly when the socket is connected. Create a buffer pool if you can handle multiple (asynchronous) receives per connection.

Upvotes: 3

Related Questions