Speed up position check for embedded length on stream I received help with adding the length of a stream in the first 4 bytes, meaning it's there as an int.

I am adding it at the start and sending it, while the receiving part checks for its position.

However, the position checking is a bit slow, so I wonder if it's possible to improve it.  Maybe using unsafe pointers or something, but I'm not sure.

currentPosition = 0;
while (currentPosition &lt; sizeof(int) &amp;&amp; tt1.Connected)
{
    currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}


There is the example on what it does at the end of the receiving part.  It goes through it, and it's a bit slow. 

I can't see much of what can be done here, but hopefully someone else has a better idea.

Here is the whole code, which may help show how it functions:

tempBytes = new byte[length];
ms = new MemoryStream(tempBytes);

int currentPosition = 0;

while (currentPosition &lt; length &amp;&amp; tt1.Connected)
{
    currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}

newImage = Image.FromStream(ms);

gmp.DrawImage(newImage, 0, 0);

currentPosition = 0;
while (currentPosition &lt; sizeof(int) &amp;&amp; tt1.Connected)
{
    currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}
length = BitConverter.ToInt32(lenArray, 0);
I agree with the comments that it's not likely to be your position checking code that's slowing you down.  Maybe you could squeeze some performance out with unsafe code, but that's maybe saving a copy from one buffer to another.  It would be nice to put that reading loop into a separate function, something like:

byte[] ReadBytes(SomeType tt1, int bytesToRead);


I can't guess what type tt1 is, but is it possible that retrieving the value for Connected is slow?  What about GetStream?