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 < sizeof(int) && 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 < length && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}

newImage = Image.FromStream(ms);

gmp.DrawImage(newImage, 0, 0);

currentPosition = 0;
while (currentPosition < sizeof(int) && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}
length = BitConverter.ToInt32(lenArray, 0);

• Any particular reason you don't want to open a BinaryReader on that stream? It'll take care of most of what you're looking for. – Jesse C. Slicer Aug 16 '13 at 20:42
• The reason is, i want to improve the speed over BinaryReader/Writer, in this case (i only send images). So trying everything there is:) – Zerowalker Aug 16 '13 at 20:43
• Are you sure the length reading is what's slowing down your code? I think it's much more likely that it's reading from disk/network/whatever that's slowing you down and there's not much you can do about that. – svick Aug 16 '13 at 21:25
• Yes and no. It´s not Slowing it down, but it´s what takes up the most time Except the reading. For reading the data takes about 24ms in this scenario, and the count thing, takes 6-9ms. Not much, but it adds up. And i am trying to improve latency by any means. Thanks – Zerowalker Aug 16 '13 at 21:44
• why does your last while loop go from currentPosition to sizof(int)? could you change that value to something smaller? – Malachi Nov 8 '13 at 19:00

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?