0
0
C Sharp (C#)programming~5 mins

StreamReader and StreamWriter in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: StreamReader and StreamWriter
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of lines grows, the time to write grows roughly the same amount.

Input Size (n)Approx. Operations
10About 10 write calls
100About 100 write calls
1000About 1000 write calls

Pattern observation: The time grows in a straight line with the number of lines.

Final Time Complexity

Time Complexity: O(n)

This means the time to write grows directly with the number of lines you write.

Common Mistake

[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.

Interview Connect

Understanding how file reading and writing scales helps you write efficient programs and answer questions about performance clearly.

Self-Check

"What if we read the file line by line using StreamReader instead of writing? How would the time complexity change?"