PHP в 5,5 раз быстрее, чем Rust в приведенном ниже примере.
Я делаю что-то в корне неправильно?
Мне кажется, что механизм регулярных выражений в 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";
Код ржавчины:
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 = "*"
Результаты
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
Спасибо!