Skip to content

Commit 071c513

Browse files
committed
TreeParser: implement LRU caching
javacc parsing is an expensive operation, so this caches the generated TreeNodes instead.
1 parent 4b96a66 commit 071c513

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

src/main/java/com/babai/ssplot/math/system/parser/ParserManager.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ private static void init() {
4242
// Engine set via envvar
4343
String engineName = System.getenv("SSPLOT_ENGINE");
4444
if (engineName == null) {
45-
engineName = TreeParser.NAME;
45+
engineName = TreeParser.internalParserName();
4646
}
4747
currParser = parsers.get(engineName);
4848
System.out.println("Using parsing engine: " + engineName);

src/main/java/com/babai/ssplot/math/system/parser/internal/tree/TreeParser.java

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,36 @@
2222

2323
package com.babai.ssplot.math.system.parser.internal.tree;
2424

25+
import java.util.LinkedHashMap;
2526
import java.util.Map;
2627
import com.babai.ssplot.math.system.parser.Parser;
2728
import com.babai.ssplot.math.system.parser.internal.SSMathParser;
2829

2930
public class TreeParser implements Parser {
30-
public static final String NAME = "Internal";
31+
private static final String NAME = "Internal";
32+
private static final Map<String, TreeNode> exprCache = new LinkedHashMap<>(16, 0.75f, true) {
33+
private static final int MAX_CACHE_ENTRIES = 100;
34+
@Override
35+
protected boolean removeEldestEntry(Map.Entry<String, TreeNode> eldest) {
36+
return size() > MAX_CACHE_ENTRIES;
37+
}
38+
};
3139

3240
@Override
33-
public double evaluate(String expression, Map<String, Double> variables) {
34-
return parse(expression).evalAt(variables);
41+
public double evaluate(String expression, Map<String, Double> variables) {
42+
// get the cached TreeNode or parse it if missing
43+
TreeNode tree = exprCache.computeIfAbsent(expression, this::parse);
44+
45+
// evaluate the cached AST with the provided variables
46+
return tree.evalAt(variables);
3547
}
3648

3749
@Override
3850
public String getName() {
51+
return internalParserName();
52+
}
53+
54+
public static String internalParserName() {
3955
return NAME;
4056
}
4157

src/main/java/com/babai/ssplot/math/system/solver/Solver.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public Vector<Vector<Double>> RK4Iterate(double x0, double y0) {
6868
return soln;
6969
}
7070

71-
Evaluator2D dx_dt = (x, y) -> parser.evaluate(system.eqns()[0], Map.of("x", x, "y", y));
71+
Evaluator2D dx_dt = (x, y) -> parser.evaluate(system.eqns()[0], Map.of("x", x, "y", y));
7272
Evaluator2D dy_dt = (x, y) -> parser.evaluate(system.eqns()[1], Map.of("x", x, "y", y));
7373

7474
double x, y;

0 commit comments

Comments
 (0)