Writing files (fwrite, file_put_contents) in PHP - Time & Space Complexity
When writing data to files in PHP, it's important to know how the time it takes grows as the data size grows.
We want to understand how the program's work changes when we write more or less data.
Analyze the time complexity of the following code snippet.
$data = str_repeat("A", 1000);
$file = fopen("example.txt", "w");
fwrite($file, $data);
fclose($file);
// Or using file_put_contents
file_put_contents("example2.txt", $data);
This code writes a string of data to a file using two common PHP functions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each byte of the string to the file.
- How many times: Once for each character in the data string.
As the size of the data string grows, the number of write operations grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 write steps |
| 100 | About 100 write steps |
| 1000 | About 1000 write steps |
Pattern observation: The work grows directly with the amount of data to write.
Time Complexity: O(n)
This means the time to write grows in a straight line with the size of the data.
[X] Wrong: "Writing to a file is always instant, no matter how big the data is."
[OK] Correct: Writing takes longer when there is more data because each byte must be saved, so time grows with data size.
Understanding how file writing time grows helps you explain performance in real projects and shows you think about efficiency clearly.
"What if we buffered the data and wrote it in chunks instead of all at once? How would the time complexity change?"