Stream 2

Stream 2 - line an expensive operation Normally output...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Stream I/O Output In issue #006 we talked about stream I/O, and an example like this was shown: cout << x << "\n"; A couple of people wrote. One said that: cout << x << endl; was preferable, while another said: cout << x << '\n'; would be a better choice on performance grounds, that is, output a single character instead of a C string containing a single character. Using one popular C++ compiler (Borland C++ 4.52), and outputting 100K lines using these three methods, the running times in seconds are: "\n" 1.9 '\n' 1.3 endl 13.2 Outputting a single character is a little simpler than outputting a string of characters, so it's a bit faster. Why is endl much slower? It turns out that it has different semantics. Besides adding a newline character like the other two forms do, it also flushes the output buffer. On a UNIX-like system, this means that ultimately a write() system call is done for each
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: line, an expensive operation. Normally, output directed to a file is buffered in chunks of size 512 or 1024 or similar. The Borland compiler has a #define called _BIG_INLINE_ in iostream.h that was enabled to do more inlining and achieve the times listed here. Does this sort of consideration matter very much? Most of the time, no. If you're doing interactive I/O, it is best to write in the style that is plainest to you and others. If, however, you're writing millions of characters to files, then you ought to pay attention to an issue like this. Note also that there's no guarantee that performance characteristics of stream I/O operations will be uniform across different compilers. It's probably true in most cases that outputting a single character is cheaper than outputting a C string containing a single character, but it doesn't have to be that way....
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online