Skip to content

Commit 51b4569

Browse files
committed
using evaluation.expr_cache to avoid recalculate
1 parent ceecb4b commit 51b4569

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

mathics/core/expression.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@
2020
# Imperical number that seems to work.
2121
# We have to be able to match mpmath values with sympy values
2222
COMPARE_PREC = 50
23+
# Expressions that should not be cached
24+
NO_CACHE_EXPR = [
25+
"System`Return",
26+
"System`Run",
27+
"System`GetEnvironment",
28+
]
2329

2430

2531
def fully_qualified_symbol_name(name) -> bool:
@@ -1301,6 +1307,21 @@ def evaluate(self, evaluation) -> typing.Union["Expression", "Symbol"]:
13011307

13021308
old_options = evaluation.options
13031309
evaluation.inc_recursion_depth()
1310+
1311+
if self.get_head_name() in NO_CACHE_EXPR:
1312+
expr_hash = None
1313+
else:
1314+
expr_hash = self.hash()
1315+
1316+
if expr_hash:
1317+
cache_expr_result = evaluation.cache_eval.get(expr_hash, None)
1318+
if cache_expr_result is not None:
1319+
expr = cache_expr_result[0]
1320+
if not expr.has_changed(definitions):
1321+
expr = cache_expr_result[1]
1322+
if not expr.has_changed(definitions):
1323+
return expr
1324+
13041325
try:
13051326
while reevaluate:
13061327
# changed before last evaluated?
@@ -1340,6 +1361,8 @@ def evaluate(self, evaluation) -> typing.Union["Expression", "Symbol"]:
13401361
evaluation.options = old_options
13411362
evaluation.dec_recursion_depth()
13421363

1364+
if expr_hash:
1365+
evaluation.cache_eval[expr_hash] = (self, expr)
13431366
return expr
13441367

13451368
def evaluate_next(self, evaluation) -> typing.Tuple["Expression", bool]:

0 commit comments

Comments
 (0)