Reputation: 58657
I was thinking about this when I ran into a problem using std::ofstream.
My thinking is that since std::ifstream, it wouldn't support random access. Rather, it would just start at the beginning and stream by until you get to the part you want. Is this just quick so we don't notice?
And I'm pretty sure FILE* supports random access so this would be fast as well?
Upvotes: 0
Views: 1052
Reputation: 54325
If you run speed comparisons on standard input or output, remember to call std::ios_base::sync_with_stdio(false)
before. When this setting is true
, then all operations are done so that reads from std::cin
pull data from the same buffers as fgets(stdin)
. Setting it to false gives iostreams more freedom and less bookkeeping.
Upvotes: 4
Reputation: 2381
std::ifstream
is a wrapper around FILE
, so the former is no way faster then the latter. How much do they differ depends on the compiler and whether it can inline wrapper function calls and perform other optimizations. Besides, reading formatted data from C++ streams is slower because they work with locales and such stuff.
However, if you often call for random access, this would be the bottleneck, as the other answers state. Anyway, the best thing is to use a profiler and measure your app performance.
Upvotes: 0
Reputation: 247969
Let's assume that FILE* was faster. Now can you give me just one good reason why std::ifstream
shouldn't be implemented in terms of that? Which means that performance becomes similar.
I'll leave the opposite case (if std::ifstream
was faster) as an exercise to the reader (hint, the same is the case there).
Before worry about performance, there is one rule of thumb you should always keep in mind:
The people who wrote your language's standard library have at least 4 working brain cells. They are not stupid.
This implies that if feature X can be trivially implemented in terms of feature Y, then X will not be noticeably slower than Y.
Upvotes: 4
Reputation: 16142
Remember that random I/O will defeat any caching done in the underlying APIs. And it is NOT going to be faster to read until you reach a particular location than to seek, regardless of which mechanism you use (assuming that your files are of any significant size).
I'm with stribika here: Measure then make a decision.
Upvotes: 0
Reputation: 3024
Since both of them imply system calls and that is going to be some orders of magnitude more time consuming that the rest of the operation, the performance of both should be very similar.
Upvotes: 5
Reputation: 3176
ifstream supports random access with seekg. FILE* might be faster but you should measure it.
Upvotes: 6