Skip to content

Commit

Permalink
add a small cache to the regex implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
hmottestad committed Dec 28, 2024
1 parent 28edab6 commit f5aeee3
Showing 1 changed file with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ public class RegexValueEvaluationStepSupplier {
private static final class ChangingRegexQueryValueEvaluationStep implements QueryValueEvaluationStep {
private final Regex node;
private final EvaluationStrategy strategy;
private Value parg;
private Value farg;
private Pattern pattern;

private ChangingRegexQueryValueEvaluationStep(Regex node, EvaluationStrategy strategy) {
this.node = node;
Expand All @@ -56,16 +59,33 @@ public Value evaluate(BindingSet bindings) throws QueryEvaluationException {

if (QueryEvaluationUtility.isStringLiteral(arg) && QueryEvaluationUtility.isSimpleLiteral(parg)
&& (farg == null || QueryEvaluationUtility.isSimpleLiteral(farg))) {

Pattern pattern = getPattern((Literal) parg, farg);

String text = ((Literal) arg).getLabel();
String ptn = ((Literal) parg).getLabel();
// TODO should this Pattern be cached?
int f = extractRegexFlags(farg);
Pattern pattern = Pattern.compile(ptn, f);
boolean result = pattern.matcher(text).find();
return BooleanLiteral.valueOf(result);
}
throw new ValueExprEvaluationException();
}

private Pattern getPattern(Literal parg, Value farg) {
if (this.parg == parg && this.farg == farg) {
return pattern;
}

String ptn = parg.getLabel();
int f = extractRegexFlags(farg);
Pattern pattern = Pattern.compile(ptn, f);

// cache the pattern object and the current parg and farg so that we can reuse it if the parg and farg are
// reused or somehow constant
this.parg = parg;
this.farg = farg;
this.pattern = pattern;

return pattern;
}
}

public static QueryValueEvaluationStep make(EvaluationStrategy strategy, Regex node,
Expand Down

0 comments on commit f5aeee3

Please sign in to comment.