Why join 7% faster than reduce?

⚓ Rust    📅 2025-12-27    👤 surdeus    👁️ 6      

surdeus

I use to use reduce to concatenate string parts with some separator. However I recently found that join works faster.

use std::error::Error;
use std::time::Instant;
use std::collections::HashMap;

fn use_join(arr: &[&str]) -> String {
    arr.into_iter().map(|curr| "\"".to_owned() +
            &json_encode(&curr) + "\"").collect::<Vec<_>>().join(", ")
}

fn use_reduce(arr: &[&str]) -> String {
    arr.into_iter().map(|curr| "\"".to_owned() +
            &json_encode(&curr) + "\"").reduce(|a,e| a + ", " + &e).unwrap_or_else(String::new)
}

fn main() -> Result<(), Box<dyn Error>> {
    let start = Instant::now();
    let mut sum = 0;
    for _ in 0..10_000_000 {
        let res = use_reduce(&opts_val);
        sum += res.len()
    }
    let duration = start.elapsed();
    println!("Time elapsed: {:?} :{sum}", duration);
    let start = Instant::now();
    let mut sum = 0;
    for _ in 0..10_000_000 {
        let res = use_join(&opts_val);
        sum += res.len()
    }
    let duration = start.elapsed();
    println!("Time elapsed for join: {:?} :{sum}", duration);

    Ok(())
}

My theory is that a closure gives overhead. What could be other reasons? Which technique do you use?

1 post - 1 participant

Read full topic

🏷️ Rust_feed