perf: use lazy thread local for regex in router match_optionals (#1309)

This commit is contained in:
Ari Seyhun 2023-07-08 22:17:52 +09:30 committed by GitHub
parent b29eb8e032
commit aef7c4ce8e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 6 deletions

View file

@ -17,6 +17,7 @@ gloo-net = { version = "0.2", features = ["http"] }
lazy_static = "1"
linear-map = { version = "1", features = ["serde_impl"] }
log = "0.4"
once_cell = "1.18"
regex = { version = "1", optional = true }
url = { version = "2", optional = true }
percent-encoding = "2"

View file

@ -3,14 +3,20 @@ use std::borrow::Cow;
#[doc(hidden)]
#[cfg(not(feature = "ssr"))]
pub fn expand_optionals(pattern: &str) -> Vec<Cow<str>> {
use js_sys::RegExp;
use once_cell::unsync::Lazy;
use wasm_bindgen::JsValue;
#[allow(non_snake_case)]
let OPTIONAL_RE = js_sys::RegExp::new(OPTIONAL, "");
#[allow(non_snake_case)]
let OPTIONAL_RE_2 = js_sys::RegExp::new(OPTIONAL_2, "");
thread_local! {
static OPTIONAL_RE: Lazy<RegExp> = Lazy::new(|| {
RegExp::new(OPTIONAL, "")
});
static OPTIONAL_RE_2: Lazy<RegExp> = Lazy::new(|| {
RegExp::new(OPTIONAL_2, "")
});
}
let captures = OPTIONAL_RE.exec(pattern);
let captures = OPTIONAL_RE.with(|re| re.exec(pattern));
match captures {
None => vec![pattern.into()],
Some(matched) => {
@ -28,7 +34,7 @@ pub fn expand_optionals(pattern: &str) -> Vec<Cow<str>> {
prefixes.push(prefix.clone());
while let Some(matched) =
OPTIONAL_RE_2.exec(suffix.trim_start_matches('?'))
OPTIONAL_RE_2.with(|re| re.exec(suffix.trim_start_matches('?')))
{
prefix += &matched.get(1).as_string().unwrap();
prefixes.push(prefix.clone());