Skip to content

Commit

Permalink
Optimize logical nodes visit methods. (#166)
Browse files Browse the repository at this point in the history
This commit provides memory optimization when visiting `LogicalNode`'s children.
Old implementation was invoking `LogicalNode#getChildren` which makes shallow copy
of its children nodes to only iterate over it we can use the fact that `LogicalNode`
is in fact `java.lang.Iterable` and use enhanced for loop to iterate over it.
Using it that way is more memory efficient and does not involve shallow copying
because iterator returned by `LogicalNode` is unmodifiable.
nstdio authored Jan 24, 2025
1 parent 9d80154 commit 5fdf6b7
Showing 1 changed file with 15 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -2,7 +2,9 @@

import static io.github.perplexhub.rsql.RSQLOperators.*;

import cz.jirutka.rsql.parser.ast.LogicalNode;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

@@ -429,14 +431,24 @@ private Predicate equalPredicate(Expression expr, Class type, Object argument) {
@Override
public Predicate visit(AndNode node, From root) {
log.debug("visit(node:{},root:{})", node, root);

return node.getChildren().stream().map(n -> n.accept(this, root)).collect(Collectors.reducing(builder::and)).get();
return visitChildren(node, root, builder::and);
}

@Override
public Predicate visit(OrNode node, From root) {
log.debug("visit(node:{},root:{})", node, root);
return visitChildren(node, root, builder::or);
}

private Predicate visitChildren(LogicalNode node, From root, BiFunction<Predicate, Predicate, Predicate> reducer) {
Predicate result = null;

for (var child : node) {
result = result != null
? reducer.apply(result, child.accept(this, root))
: child.accept(this, root);
}

return node.getChildren().stream().map(n -> n.accept(this, root)).collect(Collectors.reducing(builder::or)).get();
return result;
}
}

0 comments on commit 5fdf6b7

Please sign in to comment.