Skip to content

Instantly share code, notes, and snippets.

@shayneczyzewski
Created August 17, 2020 15:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shayneczyzewski/37608fa7bd1c1645fcefb50c35d8ea62 to your computer and use it in GitHub Desktop.
Rust vs Node performance on simple, brute-force prime check
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}`);
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);
}
time node index.js 50000
Found 50000 primes, and last is 611953
real 0m6.579s
user 0m6.571s
sys 0m0.009s
time ./target/release/prime_cli 50000
Found 50000 primes, and the last is = 611953
real 0m13.417s
user 0m13.408s
sys 0m0.000s
@shayneczyzewski
Copy link
Author

Based on the feedback here: https://users.rust-lang.org/t/rust-newbie-algorithm-performance-question/47413 changing the integer width from i64 to i32 makes Rust almost twice as fast as JS version.

let mut primes: Vec<i32> = Vec::with_capacity(num_primes);
let mut n: i32 = 2;

The i64 version took 13.5s for 50,000 primes. The i32 version is about 3.5s. :slight_smile: Node around 6.5s.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment