Writing binary array directly to binarywriter

D

dsmith

I need to write a data array out to disk, but unfortunately am running
into performance issues. The function is essentially:

private ushort[,] theInt16Array = new ushort[1200,1600];

public void Save(BinaryWriter bw)
{
/// Far too slow:
// for (int row = 0; row < Rows; row++)
// {
// for (int column = 0; column < Columns; column++)
// {
// bw.Write(theInt16Array[row, column]);
// }
// }

/// Changed to:
- byte[] byteArray = new byte[theInt16Array.Length * 2];
-
- unsafe
- {
- fixed (ushort* ushortArrayPtr = theInt16Array)
- {
- IntPtr ushortIntPtr = new IntPtr(ushortArrayPtr);
- Marshal.Copy(ushortIntPtr, byteArray, 0, byteArray.Length);
- }
- }

- bw.Write(byteArray);

}

(dashes used to ensure formatting)

The new method is about 10 times faster than the nested for-loops, but
I still need to improve on it. The main thing that I can see is the
fact that I have to copy the array every time I want to save it out
(depending on system status, this can be anywhere from 6% to 60% of
total function time). Frankly, there no good reason I can see that I
need to do that other than the fact that the Write function is limited
to writing either a single primitive value or a byte array, and there's
no way (that I know of) to treat theInt16Array as a byte array for the
duration of the write.

So, is there a better way to do this?
 
F

Frank Hileman

Buffer.BlockCopy may be faster; it can copy shorts to bytes. If you are
creating a new byte array each time you might want to make that array static
and reuse it. BinaryWriter.Write can write out any portion of a byte array.

Regards,
Frank Hileman

check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio .NET graphics editor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top