Search code examples
c++boostxcode4stdvector

Serialize a vector of floats


The problem is that I want to save a 2D vector of float in a file. since I am not familiar with C++ which is becoming troublesome, possible ways to solve are:

  1. Serializing them in a string and write to a file.
  2. Serializing them to binary data and write to a file.

Which one of the two methods could be more efficient in terms of speed?

I am doing something like:

std::string serialized;

    for (int s = 0; s < (int) mfcc_features_a.size(); s++)
     {

     for (int t = 0; t < (int) mfcc_features_a[s].size(); t++){
       serialized = serialized + "|" + boost::lexical_cast<std::string>(mfcc_features_a[s][t]);
     }
     }

    std::cout << "serialized string is: " << serialized << std::endl;

Solution

  • Storing binary data is liable to be somewhat faster, since the data will almost certainly be smaller. The difference may or may not be significant to the overall performance of your program: you'd have to measure in order to find out.

    In C++03 there is a major inefficiency in your code. specialized = specialized + "|" + ... creates gradually longer and longer copies of the full data, three copies per float value. Either use +=, or write the data directly to a stream. In C++11 you could solve it by writing specialized = std::move(specialized) + "|" + ...