SslStream has a Read method that accepts an initialized array of bytes (let's call it a buffer), an offset, and the maximum number of bytes that can be written to the buffer, and may not be written if there are not enough of them in the incoming stream. In many data exchange protocols, we do not always know the exact size of the next packet or the reception and transmission architecture built on an abstract “pipeline” in which buffers are allocated immediately for the maximum possible packet size, it can be 12 bytes, or maybe 12,000 bytes. Therefore, it is necessary to initialize a larger buffer (with a margin that often exceeds the actual number of bytes in the input stream hundreds of times), which has a detrimental effect on memory consumption and application performance.

Question : how correctly and with a bias on performance, you can override or in some other way get the packet size first (for example, reading it into some smaller temporary buffer) or the temporary buffer itself (so that you can simply replace the reference to the main buffer)?

  • And what actually prevents you from counting the length of the message first? - Pavel Mayorov
  • 2
    @ user222250 and how then do you define the message boundary? - Pavel Mayorov
  • one
    Optimizing array allocation when reading from a network? You save on matches when launching a space rocket. - VladD
  • one
    @Align: There is a suspicion that you are using the same streaming protocol, and unless your server is on the same subnet, nothing guarantees that the message will be taken in one sitting, or that there will not be several messages in the incoming data block. - VladD
  • one
    @VladD in the same subnet, too, nothing is guaranteed. Any large enough package will come in parts. - PashaPash

1 answer 1

I allocated 1024 bytes, and in a loop I increased the size of the buffer (Array.Resize ())

  • And the reason for the minus to write is not accepted? - Serg
  • one
    not minus You have posted a very incomplete superficial answer, probably the cause of a minus in this. - Kromster
  • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky
  • one
    @Serg, this option is not suitable, simply because if we get 12 kilobytes - we will have 12 allocations, and the Resize method stupidly creates a new array and copies the old one into it. - Align
  • one
    Well then, definitely not suitable. It is necessary to look at the protocol. Imap, for example, passes the size of the letter. - Serg