Background. I start out with a completely empty byte[4096]
. As data streams into my application, the byte[4096]
gets filled with data starting from first position.
This results in a byte array that is partially filled, but mostly empty, like so...
0 1 2 3 4 5 6 7 8 4096
byte[4096] --> [+][+][+][+][+][+][+][+][+][ ][ ][ ][ ][ ][ ] ... [ ]
[+] = Data
[ ] = Empty
I am trying to quickly obtain the position of the last byte with data.
My Question for Code Review
I'm looking for feedback for performance and possibly any correctness in unanticipated cases of this code block:
/// <summary>
/// Get the position of the last byte with data
/// </summary>
public static int GetPositionOfLastByteWithData(this byte[] array)
{
int i = array.Length - 1;
// find the end of the buffer by iterating backwards
while (array[i] == 0) --i;
return i;
}
Note: This method will throw an exception in the event that the byte[]
passed in is totally blank/empty. In the actual use, I do validate that there is data in the byte array before it gets to this method. This method is aimed squarely for high performance.
byte[4096]
. Thanks for pointing that out. \$\endgroup\$[+][+][+][+][ ][ ][ ][+][+][+][ ]...[ ]
). Although, I could not imagine why this would happen in 99.9% of the cases -- I just can't guarantee it. \$\endgroup\$