| | |
| | | public static class JaceCalculator |
| | | { |
| | | private static readonly CalculationEngine Engine = new CalculationEngine(); |
| | | private static readonly Dictionary<string, double> _reusableVariables = new Dictionary<string, double>(); |
| | | private static readonly object _lockObject = new object(); |
| | | |
| | | // 公式缓存,避免重复解析 |
| | | private static readonly Dictionary<string, Func<Dictionary<string, double>, double>> _formulaCache = |
| | | new Dictionary<string, Func<Dictionary<string, double>, double>>(); |
| | | |
| | | /// <summary> |
| | | /// 解析并计算数学表达式 |
| | | /// 解析并计算数学表达式(优化版本,减少GC) |
| | | /// </summary> |
| | | /// <param name="formula">数学表达式字符串</param> |
| | | /// <param name="variables">变量字典</param> |
| | |
| | | |
| | | try |
| | | { |
| | | return Engine.Calculate(formula, variables); |
| | | // 使用缓存优化 |
| | | if (!_formulaCache.TryGetValue(formula, out var compiledFormula)) |
| | | { |
| | | compiledFormula = Engine.Build(formula); |
| | | _formulaCache[formula] = compiledFormula; |
| | | } |
| | | |
| | | return compiledFormula(variables); |
| | | } |
| | | catch (Exception ex) |
| | | { |
| | |
| | | } |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 预编译常用公式,减少运行时解析开销 |
| | | /// </summary> |
| | | /// <param name="formulas">需要预编译的公式数组</param> |
| | | public static void PrecompileFormulas(params string[] formulas) |
| | | { |
| | | if (formulas == null || formulas.Length == 0) return; |
| | | |
| | | lock (_lockObject) |
| | | { |
| | | foreach (var formula in formulas) |
| | | { |
| | | if (!string.IsNullOrEmpty(formula) && !_formulaCache.ContainsKey(formula)) |
| | | { |
| | | try |
| | | { |
| | | var compiledFormula = Engine.Build(formula); |
| | | _formulaCache[formula] = compiledFormula; |
| | | } |
| | | catch (Exception ex) |
| | | { |
| | | UnityEngine.Debug.LogWarning($"Failed to precompile formula '{formula}': {ex.Message}"); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 清空公式缓存(用于内存管理) |
| | | /// </summary> |
| | | public static void ClearCache() |
| | | { |
| | | lock (_lockObject) |
| | | { |
| | | _formulaCache.Clear(); |
| | | } |
| | | } |
| | | |
| | | public static void Init() |
| | | { |
| | | Engine.AddFunction("int", (Func<double, double>)(x => (int)x)); |
| | | Engine.AddFunction("long", (Func<double, double>)(x => (long)x)); |
| | | |
| | | } |
| | | } |