So I'm learning C++ and I'm well aware that I suffer from premature optimization syndrome, but I feel like code is one of the few things in the world that can most practically aim for perfection, so I'm trying to maximize performance and efficiency here as well as develop the absolute best practices.
So there are three ways (I'm currently aware of) to do new lines:
cout << "Hello, World." << endl;
cout << "Hello, World." << "\n";
cout << "Hello, World." << '\n';
Despite that almost every beginner C++ book uses it early on, my own research has shown that endl
should be avoided unless you know you have to "clear the buffer." My understanding of what the "buffer" even is is mostly irrelevant at this point.
So that narrows it down to "\n"
and '\n'
for most cases. I then gathered that "\n"
is read as two separate characters and converted to a character. That makes it clear what to use in a situation where a newline is entered after sending a variable to an object like cout
:
int age = 25;
cout << "age = " << age << '\n'; // more efficient
cout << "age = " << age << "\n";
My main question - which is the better case when you end the statement with a string?
int age = 25;
cout << "I am " << age << " years old.\n";
cout << "I am " << age << " years old." << '\n';
One includes the \n escape character in the string, but includes an extra character. The other has the single '\n'
character but requires an extra <<
operator. Is there any way to measure which one is ultimately better? I realize I'm splitting hairs here, but I don't have the personality that allows me to get over these simple things without answers.
In a program with perhaps thousands of these types of lines, I'd like to save that fraction of CPU time if it exists. Thanks.