Rust regex replace_比PHP regex preg_replace_回调都慢,如何优化?
在下面的例子中,PHP比Rust快5.5倍 我是不是做错了什么 对我来说,Rust中的正则表达式引擎似乎比PHP中的要慢 PHP代码:Rust regex replace_比PHP regex preg_replace_回调都慢,如何优化?,php,regex,performance,optimization,rust,Php,Regex,Performance,Optimization,Rust,在下面的例子中,PHP比Rust快5.5倍 我是不是做错了什么 对我来说,Rust中的正则表达式引擎似乎比PHP中的要慢 PHP代码: $html = file_get_contents('/path_to/test.html'); global $c_id; $c_id = 0; echo 'len with comments: ', strlen($html), "\n"; $time_start = microtime(true); $html = preg_replace_cal
$html = file_get_contents('/path_to/test.html');
global $c_id;
$c_id = 0;
echo 'len with comments: ', strlen($html), "\n";
$time_start = microtime(true);
$html = preg_replace_callback('/<!--(.*?)-->/s', function($matches) {
global $c_id;
$c_id++;
return str_replace($matches[1], $c_id, $matches[0]);
}, $html);
echo (microtime(true) - $time_start), " seconds for removing comments.\n";
echo 'len without comments: ', strlen($html), "\n";
结果
PHP:
锈蚀:
谢谢 答案是使用pcre2板条箱代替生锈的regex板条箱
更多信息可以在这里找到:答案是使用pcre2板条箱代替rust中的regex板条箱
更多信息可在此处找到:您是否使用
--release
构建/运行了Rust程序?preg\u replace\u回调
应返回替换字符串。为什么不直接返回”
而不是调用str\u replace
,这可能会导致相同的结果,但代价更高?是的,但这是一个特定的示例。如果您的正则表达式不同,那么这将不起作用。是的,它是用发布模式编译的。您没有提供可复制的基准,因此实际上不可能回答这个问题。请提供所有输入,包括您的语料库。您是否使用--release
构建/运行Rust程序?preg\u replace\u callback
应返回替换字符串。为什么不直接返回”
而不是调用str\u replace
,这可能会导致相同的结果,但代价更高?是的,但这是一个特定的示例。如果您的正则表达式不同,那么这将不起作用。是的,它是用发布模式编译的。您没有提供可复制的基准,因此实际上不可能回答这个问题。请提供所有输入,包括您的语料库。
use regex::Regex;
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut file = File::open("/path_to/test.html").expect("Unable to open the file");
let mut html = String::new();
file.read_to_string(&mut html).expect("Unable to read the file");
let mut c_id: usize = 0;
println!("len with comments: {}", html.len());
let start = PreciseTime::now();
let re = Regex::new(r"(?s)<!--(.*?)-->").unwrap();
html = re.replace_all(&html, |captures: ®ex::Captures| {
c_id += 1;
captures[0].replace(&captures[1], &c_id.to_string())
}).to_string();
println!("{} seconds for removing comments.", start.to(PreciseTime::now()));
println!("len without comments: {}", html.len());
}
regex = "1"
time = "*"
len with comments: 76968
0.00019717216491699 seconds for removing comments.
len without comments: 76622
len with comments: 76968
PT0.001093365S seconds for removing comments.
len without comments: 76622