pub struct GlobalEngine;Expand description
全局单例引擎
§使用场景
- ✅ 单线程应用
- ✅ 高频率DSL执行(如配置解析、规则引擎)
- ✅ 需要最大化性能
- ❌ 多线程并发(会有锁竞争,请使用 EnginePool)
§隔离性保证
- 每次
eval_isolated()前清空环境变量 - 不同执行间的变量不会互相影响
- AST缓存跨执行保留(性能优化)
§示例
use aether::engine::GlobalEngine;
// 执行代码(隔离环境)
let result = GlobalEngine::eval_isolated("Set X 10\n(X + 20)").unwrap();
assert_eq!(result.to_string(), "30");
// 再次执行(上次的X不存在,环境已清空)
let result2 = GlobalEngine::eval_isolated("(X + 1)"); // 错误:X未定义
assert!(result2.is_err());
// 如果需要保留变量(不隔离),使用 eval()
GlobalEngine::eval("Set Y 100").unwrap();
let result3 = GlobalEngine::eval("(Y + 1)").unwrap();
assert_eq!(result3.to_string(), "101");§性能提示
对于重复执行相同代码的场景,性能提升显著:
use aether::engine::GlobalEngine;
let code = "Set X 10\n(X * 2)";
// 第一次:解析 + 缓存 + 执行
GlobalEngine::eval_isolated(code).unwrap();
// 后续执行:直接从缓存读取AST(142x faster!)
for _ in 0..1000 {
GlobalEngine::eval_isolated(code).unwrap();
}Implementations§
Source§impl GlobalEngine
impl GlobalEngine
Sourcepub fn eval(code: &str) -> Result<Value, String>
pub fn eval(code: &str) -> Result<Value, String>
使用全局引擎执行代码(非隔离,变量会累积)
警告:此方法不会清空环境,变量会在多次调用间保留。 仅在明确需要变量累积时使用。
§示例
use aether::engine::GlobalEngine;
// 第一次设置变量
GlobalEngine::eval("Set X 10").unwrap();
// 第二次可以使用X(变量保留)
let result = GlobalEngine::eval("(X + 20)").unwrap();
assert_eq!(result.to_string(), "30");
// 记得清空(如果不再需要)
GlobalEngine::clear_env();Sourcepub fn clear_cache()
pub fn clear_cache()
清空全局引擎的AST缓存
如果执行了大量不同的代码,缓存可能占用内存。 定期清理可以释放内存。
注意:清理后性能会下降,直到缓存重新建立。
Sourcepub fn cache_stats() -> Option<CacheStats>
pub fn cache_stats() -> Option<CacheStats>
获取AST缓存统计信息
返回缓存命中率、命中次数、未命中次数等信息。
Auto Trait Implementations§
impl Freeze for GlobalEngine
impl RefUnwindSafe for GlobalEngine
impl Send for GlobalEngine
impl Sync for GlobalEngine
impl Unpin for GlobalEngine
impl UnwindSafe for GlobalEngine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more