C#
String.Equals
StackOverflowException
programming
debugging

How does String.Equalsa,b not produce a StackOverflowException?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

String.Equals(a, b) compares two strings without any risk of stack overflow from string length alone because it is not implemented as recursive self-calls. It is a normal static method that performs a small number of checks and then compares characters iteratively. Large input can make it slower, but it does not make the call stack grow the way recursion does.

What Causes a StackOverflowException

A StackOverflowException happens when the program keeps adding stack frames until the process runs out of stack space. That usually comes from:

  • unbounded recursion
  • accidental cyclic method calls
  • extremely deep call chains

It does not come from simply processing a large array or a long string inside one method call.

That distinction is the key to understanding String.Equals(a, b). The method may inspect many characters, but it still does so within one ordinary call frame.

String.Equals(a, b) Is a Static Utility Method

In C#, the static overload is conceptually like this:

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        string a = "hello";
8        string b = "hello";
9
10        bool same = string.Equals(a, b);
11        Console.WriteLine(same);
12    }
13}

This does not call itself repeatedly. It performs a bounded sequence of operations:

  • reference equality check
  • null checks
  • length check
  • character comparison

None of those steps requires recursive descent through the string data.

Why Long Strings Still Do Not Grow the Stack

Suppose the strings are a million characters long. The method still does not recurse once per character. Instead, it loops over the contents internally.

A simplified illustration:

csharp
1static bool SimpleEquals(string a, string b)
2{
3    if (ReferenceEquals(a, b)) return true;
4    if (a is null || b is null) return false;
5    if (a.Length != b.Length) return false;
6
7    for (int i = 0; i < a.Length; i++)
8    {
9        if (a[i] != b[i])
10            return false;
11    }
12
13    return true;
14}

This loop may run many iterations, but the stack usage stays roughly constant because the method frame is created once and reused during the loop.

This is the same reason a for loop over ten million elements does not create ten million stack frames.

Reference Checks Make It Faster in Common Cases

Before any character-by-character comparison happens, string.Equals can often exit early.

Example:

csharp
1string x = "shared";
2string y = x;
3
4Console.WriteLine(string.Equals(x, y));

If both references point to the same string object, the method can return true immediately. That is a constant-time fast path and still involves only one method call.

Even when the references differ, length mismatches allow another quick exit:

csharp
Console.WriteLine(string.Equals("abc", "abcd"));

The method does not need recursion or complex control flow for these checks.

Stack Usage vs Heap Usage

Another source of confusion is mixing stack behavior with memory usage in general. A very large string occupies heap memory, not an ever-growing chain of stack frames.

So there are two separate questions:

  • how much memory does the string data itself use
  • how much stack does the comparison algorithm use

String.Equals works with existing string objects. It does not duplicate the full strings onto the call stack. It just keeps a few local variables and compares the contents.

Comparison Culture and Overloads

Some overloads let you specify comparison behavior such as ordinal or case-insensitive comparison.

csharp
using System;

Console.WriteLine(string.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase));

The internal logic may differ depending on the comparison mode, but the same high-level property remains true: the method is still not recursively descending through the string in a way that would create one stack frame per character.

That is why the question is really about algorithm shape, not about string size.

When a String Comparison Could Still Be Part of a Stack Overflow

A string comparison can appear in a program that eventually throws StackOverflowException, but the comparison itself is usually not the cause. For example, if two property getters call each other and one of them performs a string comparison, the recursion is still the real problem.

So the correct mental model is:

  • 'String.Equals is safe with respect to stack growth'
  • recursive code that happens to call it may still be unsafe

Common Pitfalls

The most common mistake is assuming that processing many characters must imply many stack frames. Another is confusing heap size with call-stack size, which leads to the false idea that a long string comparison is “deep” in the recursion sense. Developers also sometimes blame String.Equals when the real cause of a stack overflow is recursive property access or another cyclic call path around it. A final issue is overlooking the cheap fast paths such as reference equality and length mismatch, which make many string comparisons terminate quickly.

Summary

  • 'String.Equals(a, b) does not recurse through the string contents.'
  • Stack overflows come from unbounded stack-frame growth, not from long loop iterations.
  • String comparison uses roughly constant stack space regardless of string length.
  • Large strings affect runtime and heap usage more than stack depth.
  • If a stack overflow occurs near a string comparison, the real cause is usually recursive code around it, not the comparison itself.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.