gpt4 book ai didi

php - Rust regex replace_all 比 PHP regex preg_replace_callback 慢,如何优化?

转载 作者:行者123 更新时间:2023-11-29 08:19:44 25 4
gpt4 key购买 nike

在下面的示例中,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_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";

防 rust 代码:

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: &regex::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());
}

Rust 依赖项:

regex = "1"
time = "*"

结果

PHP:

len with comments: 76968
0.00019717216491699 seconds for removing comments.
len without comments: 76622

使用rust :

len with comments: 76968
PT0.001093365S seconds for removing comments.
len without comments: 76622

谢谢!

最佳答案

答案是在 rust 中使用 pcre2 crate 而不是 regex crate。

可在此处找到更多信息:https://users.rust-lang.org/t/rust-regex-replace-all-slower-than-php-regex-preg-replace-callback-how-to-optimize/34036/20

关于php - Rust regex replace_all 比 PHP regex preg_replace_callback 慢,如何优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58580753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com