Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(rust): update string replacement codepaths following new benchmarking #6777

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 5 additions & 18 deletions polars/polars-ops/src/chunked_array/strings/namespace.rs
Expand Up @@ -204,33 +204,20 @@ pub trait Utf8NameSpaceImpl: AsUtf8 {
out
}

/// Replace the leftmost regex-matched (sub)string with another string; take
/// fast-path for small (<= 32 chars) strings (otherwise regex faster).
/// Replace the leftmost regex-matched (sub)string with another string
fn replace<'a>(&'a self, pat: &str, val: &str) -> PolarsResult<Utf8Chunked> {
let lit = !(pat.chars().any(|c| c.is_ascii_punctuation())
| val.chars().any(|c| c.is_ascii_punctuation()));
let reg = Regex::new(pat)?;
let f = |s: &'a str| {
if lit && (s.len() <= 32) {
Cow::Owned(s.replacen(pat, val, 1))
} else {
reg.replace(s, val)
}
};
let f = |s: &'a str| reg.replace(s, val);
let ca = self.as_utf8();
Ok(ca.apply(f))
}

/// Replace the leftmost literal (sub)string with another string
fn replace_literal<'a>(&'a self, pat: &str, val: &str) -> PolarsResult<Utf8Chunked> {
// note: benchmarking shows that using the regex engine for literal
alexander-beedie marked this conversation as resolved.
Show resolved Hide resolved
// replacement is faster than str::replacen in almost all cases
let reg = Regex::new(escape(pat).as_str())?;
let f = |s: &'a str| {
if s.len() <= 32 {
Cow::Owned(s.replacen(pat, val, 1))
} else {
reg.replace(s, NoExpand(val))
}
};
let f = |s: &'a str| reg.replace(s, NoExpand(val));
let ca = self.as_utf8();
Ok(ca.apply(f))
}
Expand Down