anon
anon

Reputation:

Why fgetc too slow?

I've written a program that reads an whole file via fgetc:

while ((c = fgetc(f)) != EOF) { ... }

But the program is too slow. When I changed fgetc to fread,

static unsigned char buf[4096];

while ((n = fread(buf, 1, sizeof(buf), f)) > 0) { ... }

the program works about 10 times faster.

Why? As I know, fgetc is a buffered function, so it should work as fast as the second version with explicit buffer, isn't it?

Upvotes: 2

Views: 2434

Answers (2)

walrii
walrii

Reputation: 3522

You live close to a store. You need to get 100 cans of soup. Which is more efficient, 100 trips to the store getting 1 can each time or 1 trip to the store getting 100 cans? Obviously the 1 trip because each trip has overhead that takes time.

In the case of fgetc there are various kinds of overhead.

  • Function call
  • Is the file open?
  • At end of file?
  • Is the buffer empty?
  • Locking
  • etc.

These things can be done once for all the soup, or once for each can. Individually each bit of overhead is small but when repeated many times, the sum becomes significant.

Upvotes: 12

AProgrammer
AProgrammer

Reputation: 52284

With fgetc you not only get more function calls (each one has its overhead), but fgetc may also takes locks in multi-threaded application (this is mandated for instance by POSIX).

Upvotes: 6

Related Questions