Skip to content

Commit 24c4521

Browse files
committed
Optimize logical nodes visit methods.
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 6dfdc3d commit 24c4521

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

Lines changed: 15 additions & 3 deletions
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

@@ -417,14 +419,24 @@ private Predicate equalPredicate(Expression expr, Class type, Object argument) {
417419
@Override
418420
public Predicate visit(AndNode node, From root) {
419421
log.debug("visit(node:{},root:{})", node, root);
420-
421-
return node.getChildren().stream().map(n -> n.accept(this, root)).collect(Collectors.reducing(builder::and)).get();
422+
return visitChildren(node, root, builder::and);
422423
}
423424

424425
@Override
425426
public Predicate visit(OrNode node, From root) {
426427
log.debug("visit(node:{},root:{})", node, root);
428+
return visitChildren(node, root, builder::or);
429+
}
430+
431+
private Predicate visitChildren(LogicalNode node, From root, BiFunction<Predicate, Predicate, Predicate> reducer) {
432+
Predicate result = null;
433+
434+
for (var child : node) {
435+
result = result != null
436+
? reducer.apply(result, child.accept(this, root))
437+
: child.accept(this, root);
438+
}
427439

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

0 commit comments

Comments
 (0)