Skip to content

Commit 9c3f07f

Browse files
committed
docs: add comment on perfomance
1 parent d5e4993 commit 9c3f07f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

crates/djc-safe-eval/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,30 @@ The transformer correctly handles Python's scoping rules:
267267
- In comprehensions: Walrus assignments remain available OUTSIDE of comprehensions
268268
- In lambdas: Walrus assignments are NOT available outside
269269

270+
## Performance
271+
272+
Python expressions with `safe_eval` are 5-8x slower than if the expression was called outside of the template:
273+
274+
```py
275+
fn = safe_eval("a + b * c")
276+
fn({"a": 1, "b": 2, "c": 3})
277+
278+
# vs
279+
280+
fn = lambda ctx: ctx["a"] + ctx["b"] * ctx["c"]
281+
fn({"a": 1, "b": 2, "c": 3})
282+
```
283+
284+
This is the tradeoff for all the security checks that we do, as we have to check safety of each attribute or variable access, or function call.
285+
286+
I tried to see what would happen if I cached the results, and got about 30-50% improvement. LLM estimated that at 10,000 entries, the cache could take up ~3-5 MB. This would be relevant only to large projects, say with 500 templates, each having total of 20 tags or expressions (`{% ...%}`, `{{ }}`).
287+
288+
- For comparison, my last work project had about ~100 templates, and that was a mid-sized app that I worked on for ~1.5 years.
289+
290+
However, I removed this caching from this final PR. In django-components I think that it will be more meaningful to cache on the level of entire tags and expressions (`{% ...%}`, `{{ }}`), which will make the caching in `safe_eval` less relevant.
291+
292+
Once the Python expressions are fully integrated in django-components, and we find that these Python expressions take up non-neglibible time, we could introduce the caching.
293+
270294
## Development
271295

272296
### Dependencies

0 commit comments

Comments
 (0)