DEV Community

Sabin Sim
Sabin Sim

Posted on

33. C# (Loop Performance)

0. The Real Goal of This Lesson

This lesson is not just a warning about slow code.

The key idea is this:

Loops multiply execution time.
Performance problems often come from multiplication, not addition.

Today the goal is to understand the structure of execution time, not just that something “can be slow.”


1. Why This Concept Matters

In real development you will eventually:

  • build API servers
  • connect databases
  • process user requests
  • traverse collections
  • process large datasets

The most dangerous combination is:

nested loops + expensive operations
(database queries, file I/O, network calls, external APIs)

A loop is not just a structure that repeats work.

A loop multiplies the cost of the work inside it.


2. What Program Performance Really Means

In simple terms:

Performance describes how quickly a program runs
and how many resources it consumes.

Typical resources include:

  • CPU computation time
  • memory usage
  • disk access
  • network requests
  • database calls

But the key mindset shift is this:

Performance is not about asking:

“Is this line of code fast?”

Instead, ask:

“How many times will this code run?”


3. Execution Flow of a Nested Loop

Example:

using System;

class Program
{
    static void Main()
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 15; j++)
            {
                Console.WriteLine($"i={i}, j={j}");
            }
        }

        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution sequence:

  1. i = 0 → inner loop runs 15 times
  2. i = 1 → inner loop runs 15 times
  3. i = 2 → inner loop runs 15 times
  4. i = 3 → inner loop runs 15 times

Total executions:

4 × 15 = 60
Enter fullscreen mode Exit fullscreen mode

Because Console.WriteLine is fast, you do not notice the cost.

But the real issue is:

operation cost × execution count


4. What If the Inner Operation Takes 100 ms?

Example:

for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 15; j++)
    {
        System.Threading.Thread.Sleep(100);
    }
}
Enter fullscreen mode Exit fullscreen mode

Calculation:

1 execution = 100 ms
60 executions = 6000 ms
Enter fullscreen mode Exit fullscreen mode

Total runtime:

6 seconds
Enter fullscreen mode Exit fullscreen mode

From a user's perspective:

“Did the server freeze?”

The key insight:

Loops do not simply add time —
they multiply it.


5. Optimization Strategy 1 — Early Exit with break

If the purpose of the loop is searching, stop when the item is found.

Inefficient version:

int[] numbers = { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] == 2)
    {
        Console.WriteLine("Found!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Even after finding the value, the loop continues.

Improved version:

for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] == 2)
    {
        Console.WriteLine("Found!");
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution flow:

1 → check
2 → found
break → loop stops immediately
Enter fullscreen mode Exit fullscreen mode

This avoids unnecessary work.


6. Optimization Strategy 2 — Move Expensive Work Outside the Loop

A common mistake:

for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 15; j++)
    {
        var data = GetDataFromDatabase();
        Console.WriteLine(data);
    }
}
Enter fullscreen mode Exit fullscreen mode

Database calls:

4 × 15 = 60
Enter fullscreen mode Exit fullscreen mode

Database operations are far slower than CPU operations.

Better structure:

var data = GetDataFromDatabase();

for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 15; j++)
    {
        Console.WriteLine(data);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the database call occurs:

1 time instead of 60
Enter fullscreen mode Exit fullscreen mode

The key question developers should ask:

Does this operation need to run every iteration?

Or:

Can it run once outside the loop?


7. How Execution Grows with Nested Loops

Execution growth pattern:

Single loop:

n
Enter fullscreen mode Exit fullscreen mode

Two nested loops:

n × m
Enter fullscreen mode Exit fullscreen mode

Three nested loops:

n × m × k
Enter fullscreen mode Exit fullscreen mode

Each additional nesting level multiplies the total work.

This is why nested loops are strongly related to algorithmic complexity.


8. Common Performance Mistakes

Mistake Result
Database calls inside inner loops Slow response time
No early exit during search Unnecessary CPU usage
Deep nesting (3+ loops) Explosive execution count
Repeating identical calculations Wasted resources

9. Practical Perspective

In real applications you will work with:

  • .NET APIs
  • FastAPI or web services
  • database queries
  • large collections
  • data processing pipelines

In those systems the most important question is:

How many times does this code run?

Syntax comes second.

Execution count comes first.


Final Summary

A loop multiplies execution time.
Putting expensive operations inside nested loops can make performance degrade exponentially.


Thinking Question

Suppose an API processes 10,000 records.

Which of the following operations should never be placed inside a loop?

  1. Database queries
  2. External API calls
  3. File I/O operations
  4. Simple variable increments

Explain your reasoning in terms of execution count and cost per operation.

Top comments (0)