perf(linter/no-unescaped-entities): add fast path to check if char should be replaced (#6594)

Flamegraph shows a lot of time spent hashing here, so I added a faster check to see if it is a char that we need to replace.
This commit is contained in:
camchenry 2024-10-16 19:59:30 +00:00
parent ee73f568b3
commit b3d0cce2c2

View file

@ -51,6 +51,9 @@ impl Rule for NoUnescapedEntities {
if let AstKind::JSXText(jsx_text) = node.kind() { if let AstKind::JSXText(jsx_text) = node.kind() {
let source = jsx_text.span.source_text(ctx.source_text()); let source = jsx_text.span.source_text(ctx.source_text());
for (i, char) in source.char_indices() { for (i, char) in source.char_indices() {
if !CHARS.contains(&char) {
continue;
}
if let Some(escapes) = DEFAULTS.get(&char) { if let Some(escapes) = DEFAULTS.get(&char) {
#[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_possible_truncation)]
ctx.diagnostic(no_unescaped_entities_diagnostic( ctx.diagnostic(no_unescaped_entities_diagnostic(
@ -71,6 +74,9 @@ impl Rule for NoUnescapedEntities {
} }
} }
// NOTE: If we add substantially more characters, we should consider using a hash set instead.
pub const CHARS: [char; 4] = ['>', '"', '\'', '}'];
pub const DEFAULTS: Map<char, &'static [&'static str]> = phf_map! { pub const DEFAULTS: Map<char, &'static [&'static str]> = phf_map! {
'>' => &["&gt;"], '>' => &["&gt;"],
'"' => &["&quot;", "&ldquo;", "&#34;", "&rdquo;"], '"' => &["&quot;", "&ldquo;", "&#34;", "&rdquo;"],