Rust vs Node performance on simple, brute-force prime check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const num_primes = parseInt(process.argv[2], 10); | |
const primes = new Array(); | |
let n = 2; | |
while (primes.length < num_primes) { | |
if (!primes.find(p => n % p === 0)) { | |
primes.push(n); | |
} | |
n += 1; | |
} | |
console.log(`Found ${primes.length} primes, and last is ${n - 1}`); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let num_primes = args.get(1).unwrap().parse::<usize>().unwrap(); | |
let mut primes: Vec<i64> = Vec::with_capacity(num_primes); | |
let mut n: i64 = 2; | |
while primes.len() < num_primes { | |
if let None = primes.iter().find(|&&p| n % p == 0) { | |
primes.push(n); | |
} | |
n += 1; | |
} | |
println!("Found {} primes, and the last is = {}", primes.len(), n - 1); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
time node index.js 50000 | |
Found 50000 primes, and last is 611953 | |
real 0m6.579s | |
user 0m6.571s | |
sys 0m0.009s |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
time ./target/release/prime_cli 50000 | |
Found 50000 primes, and the last is = 611953 | |
real 0m13.417s | |
user 0m13.408s | |
sys 0m0.000s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on the feedback here: https://users.rust-lang.org/t/rust-newbie-algorithm-performance-question/47413 changing the integer width from
i64
toi32
makes Rust almost twice as fast as JS version.The i64 version took 13.5s for 50,000 primes. The i32 version is about 3.5s. :slight_smile: Node around 6.5s.