Skip to content

Commit 5fdf6b7

Browse files
authored
Optimize logical nodes visit methods. (#166)
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.
1 parent 9d80154 commit 5fdf6b7

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

rsql-jpa/src/main/java/io/github/perplexhub/rsql/RSQLJPAPredicateConverter.java

+15-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

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

5+
import cz.jirutka.rsql.parser.ast.LogicalNode;
56
import java.util.*;
7+
import java.util.function.BiFunction;
68
import java.util.function.Function;
79
import java.util.stream.Collectors;
810

@@ -429,14 +431,24 @@ private Predicate equalPredicate(Expression expr, Class type, Object argument) {
429431
@Override
430432
public Predicate visit(AndNode node, From root) {
431433
log.debug("visit(node:{},root:{})", node, root);
432-
433-
return node.getChildren().stream().map(n -> n.accept(this, root)).collect(Collectors.reducing(builder::and)).get();
434+
return visitChildren(node, root, builder::and);
434435
}
435436

436437
@Override
437438
public Predicate visit(OrNode node, From root) {
438439
log.debug("visit(node:{},root:{})", node, root);
440+
return visitChildren(node, root, builder::or);
441+
}
442+
443+
private Predicate visitChildren(LogicalNode node, From root, BiFunction<Predicate, Predicate, Predicate> reducer) {
444+
Predicate result = null;
445+
446+
for (var child : node) {
447+
result = result != null
448+
? reducer.apply(result, child.accept(this, root))
449+
: child.accept(this, root);
450+
}
439451

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

0 commit comments

Comments
 (0)