Skip to content

Commit

Permalink
Improve ClassCondition performance (danfickle#8)
Browse files Browse the repository at this point in the history
fixes danfickle#1

---------

Co-authored-by: Zachary Siegel <[email protected]>
  • Loading branch information
jochenberger and siegelzc authored Feb 7, 2024
1 parent c6a660f commit 2499261
Showing 1 changed file with 13 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -371,10 +371,10 @@ void toCSS(StringBuilder sb) {

private static class ClassCondition extends Condition {

private String _paddedClassName;
private String _className;

ClassCondition(String className) {
_paddedClassName = " " + className + " ";
_className = className;
}

@Override
Expand All @@ -383,20 +383,28 @@ boolean matches(Object e, AttributeResolver attRes, TreeResolver treeRes) {
return false;
}
String c = attRes.getClass(e);
if (c == null) {
if (c == null || c.length() < _className.length()) {
return false;
}

// This is much faster than calling `split()` and comparing individual values in a loop.
// NOTE: In jQuery, for example, the attribute value first has whitespace normalized to spaces. But
// in an XML DOM, space normalization in attributes is supposed to have happened already.
return (" " + c + " ").indexOf(_paddedClassName) != -1;
int idx = c.indexOf(_className);
if (idx == -1){
return false;
}
int beforeMatch = idx - 1;
int afterMatch = idx + _className.length();
boolean delimitedBefore = beforeMatch < 0 || Character.isWhitespace(c.charAt(beforeMatch));
boolean delimitedAfter = afterMatch == c.length() || Character.isWhitespace(c.charAt(afterMatch));
return delimitedBefore && delimitedAfter;
}

@Override
public void toCSS(StringBuilder sb) {
sb.append('.');
sb.append(_paddedClassName.substring(1, _paddedClassName.length() - 1));
sb.append(_className);
}
}

Expand Down

0 comments on commit 2499261

Please sign in to comment.