2

I have a 2D array and would like to store in a binary file. To my knowledge, I wrote the following code to transfer the data into a binary file.

double[,] A = new double[nx,ny];
// put some data in the array
for (i = 0; i < nx ; i++)
{
    for (j = 0; j < ny ; j++)
    {
        A[i,j] = ...;
    }
}
string path = "address";
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
for (i = 0; i < nx ; i++)
{
    for (j = 0; j < ny ; j++)
    {
        bw.Write(A[i,j]);
    }
}
bw.Close();
fs.Close();

This code works, but I need better way and faster method. Any idea?

6
  • 4
    Whatever you do, start by benchmarking the performance so you can compare solutions. And then establish an expectation for what you'll consider "good enough" performance. How long does this take with the size of data that you have? Commented Aug 13, 2014 at 5:05
  • 1
    The BinaryFormatter will be the easiest. It Serializes pretty efficiently. Commented Aug 13, 2014 at 5:07
  • 1
    Writing to disk is what expensive here, x1000s more than anything in memory. Focus there (maybe buffering writes into bigger chunks etc.) Commented Aug 13, 2014 at 5:19
  • 2
    Writing 1 double at a time is not good. Store in continuous byte[] array(s) and write that at one go if possible. You can convert double to bytes using the BitConverter.GetBytes(double) method. Commented Aug 13, 2014 at 5:26
  • Do it as @Loathing said: Convert (in memory) to a byte array, then write this to file in one go. If the array is really large, do the process steps for each row. Commented Aug 13, 2014 at 5:42

1 Answer 1

2

You can use binary serialization with the BinaryFormatter Class.

You will find lots of information in the net. One example is: http://www.centerspace.net/examples/nmath/csharp/core/binary-serialization-example.php

Sign up to request clarification or add additional context in comments.

2 Comments

BinaryFormatter is not well suited for persistent storage. If the assembly version changes for any of the types that are stored in your serialized file you will not be able to perform the deserialization. The intent of BinaryFormater is to be used for IPC communication on the same system, not for network transmission nor persistent storage.
BinaryFormatter is also slow. The question is asking for a FAST method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.