What is the preferred way to write string to file in C++, use '+' or several '<<'?

Viewed 110

I am considering writing several lines into a file in C++ using ofstream and the text is composed of several parts (strings and numbers), so essentially I know there are two ways.

Here is a simple example:

// Way 1 (Use several '<<')
f << str1 << " " << 10 << "Text" << std::endl;
// Way 2 (Use plus to have a continuous string)
f << str1 + " " + std::to_string(10) + "Text" << std::endl;

So which one is preferred (or maybe use append instead of +) in terms of efficiency and other criteria?

1 Answers

I wrote a small program that tries both methods, the first version, using << seems to be faster. In any case, the usage of std::endl inhibits performance significantly, so I've changed it to use \n.

#include <iostream>
#include <fstream>
#include <chrono>

int main () {
    unsigned int iterations = 1'000'000;
    std::string str1 = "Prefix string";

    std::ofstream myfile;
    myfile.open("example.txt");

    auto start = std::chrono::high_resolution_clock::now();
    for (int i=0; i < iterations; i++) {
        myfile << str1 << " " << 10 << "Text" << "\n";
    }
    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = stop - start;
    std::cout << "Duration: " << duration.count() << std::endl;

    std::ofstream myfile2;
    myfile2.open("example2.txt");

    start = std::chrono::high_resolution_clock::now();
    for (int i=0; i < iterations; i++) {
        myfile2 << str1 + " " + std::to_string(10) + "Text" << "\n";
    }
    stop = std::chrono::high_resolution_clock::now();
    duration = stop - start;
    std::cout << "Duration: " << duration.count() << std::endl;

    myfile.close();
    return 0;
}

And the output on my machine:

Duration: 91549609
Duration: 216557352
Related