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?
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?