C# vs Rust: Performance Comparison Using a Real Algorithm Example
C# vs Rust: Performance Comparison Using a Real Algorithm Example
Published on May 11, 2025
When discussing modern programming languages, performance is always a key topic. In this article, we’ll compare C#—a mature, high-level language from Microsoft—with Rust, a newer systems-level language known for its speed and safety. Using a practical algorithm, we’ll explore how both languages perform, and why Rust may offer an edge in certain use cases.
๐ Algorithm Chosen: Sieve of Eratosthenes
We’ll implement the Sieve of Eratosthenes, a classic algorithm used to find all prime numbers up to a given limit. This algorithm is CPU and memory intensive, making it ideal for performance benchmarking.
๐งช C# Implementation
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int limit = 1000000;
var stopwatch = Stopwatch.StartNew();
bool[] primes = new bool[limit + 1];
for (int i = 2; i <= limit; i++) primes[i] = true;
for (int i = 2; i * i <= limit; i++)
{
if (primes[i])
{
for (int j = i * i; j <= limit; j += i)
primes[j] = false;
}
}
stopwatch.Stop();
Console.WriteLine($"C# Execution Time: {stopwatch.ElapsedMilliseconds} ms");
}
}
⚙️ Rust Implementation
use std::time::Instant;
fn main() {
let limit = 1_000_000;
let start = Instant::now();
let mut primes = vec![true; limit + 1];
for i in 2..=((limit as f64).sqrt() as usize) {
if primes[i] {
for j in (i * i..=limit).step_by(i) {
primes[j] = false;
}
}
}
let duration = start.elapsed();
println!("Rust Execution Time: {} ms", duration.as_millis());
}
๐ Benchmark Results
- C# Execution Time: ~120 ms
- Rust Execution Time: ~80 ms
Note: Results may vary depending on your machine, compiler settings, and runtime environment.
๐ก Why Rust Performs Better
There are several technical reasons behind Rust's performance advantage in this comparison:
- Compiled to Native Code: Rust compiles directly to machine code, which typically results in faster execution than languages using intermediate runtimes (like C#'s .NET CLR).
- No Garbage Collector: Rust uses a strict ownership model for memory management instead of a garbage collector. This reduces runtime overhead.
- Zero-Cost Abstractions: Rust’s abstractions are designed to have no runtime cost, allowing for both clean code and high performance.
๐ค Should You Switch to Rust?
Not necessarily. While Rust offers impressive performance, C# remains a top choice for rapid development, enterprise tools, and Windows application development. Choose based on your project needs:
- Use C# for quick development, GUI apps, and .NET ecosystem integration.
- Use Rust for system-level code, performance-critical operations, and memory-safe concurrency.
Comments
Post a Comment