Why fgetc too slow?

后端 未结 2 1787
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题