Why fgetc too slow?

后端 未结 2 1763
死守一世寂寞
死守一世寂寞 2021-01-23 01:26

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

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

But the program is too slow. Whe

相关标签:
2条回答
  • 2021-01-23 01:48

    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).

    0 讨论(0)
  • 2021-01-23 01:59

    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.

    0 讨论(0)
提交回复
热议问题