DEV Community

Sabin Sim
Sabin Sim

Posted on

26. C# (Loop Performance)

0. The Real Goal of This Lesson

Loops do not increase execution time additively.
They increase it multiplicatively.

This is not a warning.

It is structural analysis.

If you misunderstand this:

  • Your API becomes slow
  • Your database melts
  • Your server “mysteriously” stalls

Performance degradation is not linear.

It compounds.


1. Why This Concept Is Necessary

As you build:

  • API servers
  • Database integrations
  • Request handlers
  • Collection processors
  • Large-scale data pipelines

The most dangerous combination is:

Nested loops + heavy operations (DB, file I/O, network, external API)

A loop does not “add time.”

It multiplies time.


2. What Is Program Performance?

Definition:

How fast a program runs
How many resources it consumes

Resources include:

  • CPU time
  • Memory
  • Disk access
  • Network calls
  • Database queries

The key shift:

Performance is not about:

“Is this code fast?”

It is about:

“How many times does this code execute?”

Execution count defines cost.


3. Dissecting Nested Loop Execution

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 Timeline

  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

Console.WriteLine is lightweight.

So you don’t feel the cost.

But performance is:

Cost per execution × number of executions


4. What If Each Inner Operation Takes 100ms?

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 = 100ms
60 executions = 6000ms

6 seconds.

From the user’s perspective:

“Is the server frozen?”

Key insight:

Loops multiply time.

They do not merely add time.


5. Optimization Strategy 1 — Early Termination with break

If the loop’s purpose is searching:

Stop when found.

Bad 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

Problem:

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 stops immediately.

Unnecessary iterations are eliminated.


6. Optimization Strategy 2 — Move Heavy Operations Outside the Loop

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 call count:

4 × 15 = 60 DB calls
Enter fullscreen mode Exit fullscreen mode

Database operations are expensive.

Improved 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:

1 DB call
Enter fullscreen mode Exit fullscreen mode

Critical question:

Does this operation need to run every iteration?
Or only once?

This question defines performance maturity.


7. Growth Pattern of Nested Loops

One loop:

n
Enter fullscreen mode Exit fullscreen mode

Two loops:

n × m
Enter fullscreen mode Exit fullscreen mode

Three loops:

n × m × k
Enter fullscreen mode Exit fullscreen mode

Each level multiplies execution count.

This is exponential growth in practical terms.

In complexity notation:

O(n)
O(n²)
O(n³)
Enter fullscreen mode Exit fullscreen mode

Nested loops scale aggressively.


8. Common Performance Mistakes

Mistake Result
DB call inside inner loop Severe latency
No early exit Unnecessary CPU usage
Deep nesting (3+) Explosive execution count
Recomputing identical values Resource waste

Performance bugs are often structural.

Not algorithmic.


9. Long-Term Perspective

As you move toward:

  • FastAPI / .NET APIs
  • Database integrations
  • AI data processing
  • Large collection filtering

The most important question is:

How many times does this execute?

Not:

Is the syntax correct?

Execution count determines scalability.


10. Final Summary

A loop multiplies execution time.
Placing heavy operations inside nested loops causes exponential performance degradation.


Final Question

If your API processes 10,000 records,

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

  1. Database call
  2. External API request
  3. File I/O
  4. Simple variable increment

The answer reveals whether you think additively or multiplicatively.

Top comments (0)