String replace - Is Rust really slower than JavaScript?

I want to reimplement some JavaScript Code using Rust. Since the JavaScript code use "replaceAll" for large Strings (~5MB) I compare the performance of Rust and JavaScript regarding replace.

You can find my code here:

It seems that JavaScript is faster in this case. Have I missed something?
Best regards

1 Like

JavaScript's replaceAll is powered by its regex engine, while Rust's standard library includes only naive string matching.

Using the Rust regex crate makes the Rust version about 9 times faster on my machine:

use std::time::Instant;
use std::fs::{read_to_string};

fn main() {
    let text = read_to_string("../string.json").unwrap();
    let pattern = regex::Regex::new("http://localhost:35261/product").unwrap();
    let parse = Instant::now();
    let _result = pattern.replace_all(&text, "");
    println!("Replace {} nanos", parse.elapsed().as_nanos());

(Or “only” 5 times faster if you include the time to compile the Regex.)


Is it possible to look at the codegen being used by the Javascript example?

The main difference between std's search-and-replace and regex's is that std doesn't have any vectorization in it to accelerate it for common cases. That isn't the complete story, but it probably explains observed differences 90% of the time.

I would suppose that something as sophisticated as Javascript's regex engine uses vectorization for such cases.

Wow! That was a quick and very, very helpful response. I need to compile the regex at runtime. Now the performance between Rust and JavaScript are the same in this special case - which is my expectation.

I think in Node.js you can roughly instrument v8 with :

const v8 = require('v8');
v8.setFlagsFromString('--code-comments --print-code');

I imagine Deno has a similar thing ?

@Charles5214 Please open a new thread.