StreamReader and StreamWriter in C Sharp (C#) - Time & Space Complexity
When working with files in C#, we often use StreamReader and StreamWriter to read and write text.
We want to understand how the time it takes to read or write grows as the file size grows.
Analyze the time complexity of the following code snippet.
using System.IO;
void WriteLines(string filePath, string[] lines)
{
using var writer = new StreamWriter(filePath);
foreach (var line in lines)
{
writer.WriteLine(line);
}
}
This code writes each string from an array to a file line by line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop writes each line to the file.
- How many times: It runs once for every line in the input array.
As the number of lines grows, the time to write grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 write calls |
| 100 | About 100 write calls |
| 1000 | About 1000 write calls |
Pattern observation: The time grows in a straight line with the number of lines.
Time Complexity: O(n)
This means the time to write grows directly with the number of lines you write.
[X] Wrong: "Writing to a file is instant and does not depend on the number of lines."
[OK] Correct: Each line requires a write operation, so more lines mean more work and more time.
Understanding how file reading and writing scales helps you write efficient programs and answer questions about performance clearly.
"What if we read the file line by line using StreamReader instead of writing? How would the time complexity change?"