C++ much faster than Bash script writing to text file

Viewed 4425

I wanted to test the performance of writing to a file in a bash script vs a C++ program.

Here is the bash script:

#!/bin/bash

while true; do
        echo "something" >> bash.txt
done

This added about 2-3 KB to the text file per second.

Here is the C++ code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ofstream myfile;
    myfile.open("cpp.txt");

    while (true) {
        myfile << "Writing this to a file Writing this to a file \n";
    }

    myfile.close();
}

This created a ~6 GB text file in less than 10 seconds.

What makes this C++ code so much faster, and/or this bash script so much slower?

3 Answers
Related