perf: skip regex in getClassesAndAttr when no \t\r\n present

getClassesAndAttr unconditionally ran rxClassTrim.ReplaceAllString to
normalize tabs, carriage returns, and newlines in class attribute values.
The vast majority of HTML class attributes contain none of these, so add
a strings.ContainsAny fast path that falls back to simple concatenation.

This benefits all callers: HasClass, AddClass, RemoveClass, ToggleClass. Here's
a benchmark of HasClass to illustrate the gains:

name          old ns/op   new ns/op   delta
HasClass-8    222000      45300       -79.6%

name          old B/op    new B/op    delta
HasClass-8    19152       4280        -77.6%

name          old allocs  new allocs  delta
HasClass-8    1300        325         -75.0%
This commit is contained in:
jvoisin
2026-05-23 23:11:00 +02:00
parent 33466f5bcd
commit 3c647f82fe
+3 -1
View File
@@ -243,8 +243,10 @@ func getClassesAndAttr(n *html.Node, create bool) (classes string, attr *html.At
if attr == nil {
classes = " "
} else {
} else if strings.ContainsAny(attr.Val, "\t\r\n") {
classes = rxClassTrim.ReplaceAllString(" "+attr.Val+" ", " ")
} else {
classes = " " + attr.Val + " "
}
return