Writing text files in C Sharp (C#) - Time & Space Complexity
When writing text files, it's important to understand how the time it takes grows as the file size grows.
We want to know how the program's work changes when we write more lines or characters.
Analyze the time complexity of the following code snippet.
using System.IO;
string[] lines = new string[] { "Line1", "Line2", "Line3" };
using StreamWriter writer = new StreamWriter("output.txt");
foreach (string line in lines)
{
writer.WriteLine(line);
}
This code writes each line from an array into a text file, one line at a time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each line to the file inside a loop.
- How many times: Once for each line in the input array.
As the number of lines increases, the program writes more times, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 write operations |
| 100 | 100 write operations |
| 1000 | 1000 write operations |
Pattern observation: The number of write actions grows directly with the number of lines.
Time Complexity: O(n)
This means the time to write grows in a straight line as the number of lines grows.
[X] Wrong: "Writing a file always takes the same time no matter how big it is."
[OK] Correct: Writing more lines means more work, so time grows with file size.
Understanding how file writing time grows helps you explain performance in real programs that save data.
"What if we buffered all lines into one big string and wrote once? How would the time complexity change?"