Hi,
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.
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, "http://example.com/product");
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.