Performance: Single char vs block I/O
What you'll learn: Why reading or writing data in large chunks is significantly faster than processing it one character at a time.
The Post Office Analogy
Imagine you are moving 100 letters to the post office. You have two choices:
- Walk to the post office, drop off one letter, walk home, and repeat this 100 times.
- Put all 100 letters in a single box, walk to the post office once, and drop them all off.
The second method is vastly more efficient. In programming, every time your code asks the Operating System (OS) to read or write to a disk or a screen, it’s like making that long walk to the post office. This is called a System Call, and it is "expensive" in terms of time and processing power.
Single Character I/O
Functions like fgetc() or fputc() handle one character at a time. While easy to use, they can be slow if used in a loop to move large amounts of data. Even though C uses internal "buffering" to help speed this up, calling a function thousands of times creates unnecessary overhead.
Block I/O
Block I/O uses functions like fread() and fwrite(). These allow you to move a large "buffer" (a chunk of memory) in a single operation. Instead of 1,000 tiny requests, you make one big request. This minimizes the communication overhead between your program and the hardware.
Concrete Example
Compare these two conceptual approaches to copying a file:
// APPROACH 1: Slow (Single Character)
char ch;
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}
// APPROACH 2: Fast (Block I/O)
char buffer[4096]; // A 4KB "box"
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
fwrite(buffer, 1, bytesRead, destination);
}
In the second example, we handle 4,096 characters at once. This reduces the number of function calls and system interactions by a factor of 4,000, leading to a massive performance boost, especially when dealing with large files or network data.
Key takeaway
Minimize system overhead by using fread and fwrite to process data in large buffers rather than character by character.