dotnet / dotnet/runtime

C# Recursive Function is Slower than Java

Open
#122,302 9 comments 7 reactions 0 assignees View on GitHub
area-CodeGen-coreclr tenet-performance
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### 🐛 Description of the Issue

When comparing the performance of a simple, CPU-intensive iterative loop between the latest .NET (assumed to be .NET 10) and Java (assumed to be Java 25, tested with sufficient warmup), the C# code is consistently performing approximately **100% slower (twice the execution time)**.

The test scenario involves a deeply nested loop structure executing a non-recursive, iterative function 10 million times. Since the recursive overhead has been removed, the expected performance gap should be minimal, if any. The observed result suggests a potential sub-optimal JIT compilation or a lack of aggressive optimization (such as method inlining or loop invariant code motion) within the C# Runtime/RyuJIT compiler for this specific high-frequency iterative pattern.

### 🧪 Environment (Please complete the following details)

* **.NET Version:** [Specify the exact version, e.g., .NET10]
* **Java Version:** [Specify the exact version, e.g., Java 25 LTS]
* **Operating System:** [e.g., Windows 11]
* **CPU Architecture:** [e.g., x64,]

### 💻 Code Snippet (C# - Slow Example)

*(Note: Replace AFunction with your actual iterative, non-recursive code)*

```csharp
using System.Diagnostics;
namespace ConsoleApp1;
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = Stopwatch.StartNew();
long a = 0;
for (int v = 0; v < 10000; v++)
{
for (int i = 0; i <10000; i++)
{
a+=AFunction(10+v%2);
}
}
stopwatch.Stop();
Console.WriteLine($"{a}, Execution Time: {stopwatch.ElapsedMilliseconds} ms");

}
public static int AFunction(int v)
{
if (v <= 0)
{
return v;
}

return AFunction((v-1)/2)+AFunction((v-2)/2);
}
}
```

Image

### 💻 Code Snippet (Java - Slow Example)

*(Note: Replace AFunction with your actual iterative, non-recursive code)*

```java
package org.example;

public class Main {
static void main() {
long start = System.currentTimeMillis();
int a=0;
for(int v=0;v<10000;v++){
for(int i=0;i<10000;i++){
a+=AFunction(10+v%2);
}
}
long end = System.currentTimeMillis();
System.out.println(end-start+" time :"+a);
}
static int AFunction(int v) {
if(v<=0){
return v;
}
return AFunction((v-1)/2)+AFunction((v-2)/2);
}
}

```

Image

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.