Search code examples
c++fstream

Theoretical perfomance difference between multiple get() and single getline() in fstream


Say I'm reading from a file.

ifstream f("file.txt");

while (f.good())
{
  char c = is.get();
}

VS

ifstream f("file.txt");
string line;
while(f.good())
{
  getline(f, line);
}

Does it theoretically make a difference given the file handle is left open throughout the entire file read?


Solution

  • Depends.

    If your stream isn't cached, there might be a noticeable difference between the two versions. If for some reason you don't open a file but rather a memory stream that is extremely fast, the multiple calls to get might be slower. That, of course, also depends on how getline is implemented.

    So there is a theoretical difference. Of course, to see if there's an actual difference, you should try it out. Chances are you don't notice any difference.