Why file operations matter in PHP - Performance Analysis
File operations can take different amounts of time depending on how much data you read or write.
We want to know how the time needed grows when the file size changes.
Analyze the time complexity of the following code snippet.
// Read a file line by line and print each line
$handle = fopen('example.txt', 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
This code opens a file and reads it line by line until the end, printing each line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line from the file inside the while loop.
- How many times: Once for every line in the file, depending on file size.
As the file gets bigger, the number of lines grows, so the reading steps grow too.
| Input Size (lines) | Approx. Operations |
|---|---|
| 10 | About 10 reads and prints |
| 100 | About 100 reads and prints |
| 1000 | About 1000 reads and prints |
Pattern observation: The time grows directly with the number of lines in the file.
Time Complexity: O(n)
This means the time to read the file grows in a straight line with the file size.
[X] Wrong: "Reading a file always takes the same time no matter how big it is."
[OK] Correct: The bigger the file, the more lines or data you have to read, so it takes longer.
Understanding how file size affects reading time helps you write better programs that handle data efficiently.
"What if we read the whole file at once instead of line by line? How would the time complexity change?"