From be37a4ed4059ce79321c5e3f2438934866ec7be5 Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Fri, 19 Jan 2024 20:14:57 +0100 Subject: add function_cache for performence gain --- src/function_cache.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/function_cache.rs (limited to 'src/function_cache.rs') diff --git a/src/function_cache.rs b/src/function_cache.rs new file mode 100644 index 0000000..d4beb16 --- /dev/null +++ b/src/function_cache.rs @@ -0,0 +1,32 @@ +use std::collections::HashMap; + +use crate::math::{ + complex::Complex, context::Context, expression_function::ExpressionFunction, + function::{FunctionArgument, Function}, +}; + +#[derive(Default)] +pub struct FunctionCache { + func: ExpressionFunction, + cache: HashMap, +} + +impl FunctionCache { + pub fn new(func: ExpressionFunction) -> Self { + Self { + func, + cache: HashMap::new(), + } + } + + pub fn eval(&mut self, x: Complex, ctx: &Context) -> Complex { + if self.cache.contains_key(&x) { + *self.cache.get(&x).unwrap() + } else { + let fargs = FunctionArgument::from_values(vec![x]); + let v = self.func.eval(&fargs, ctx).unwrap(); + self.cache.insert(x, v); + v + } + } +} -- cgit v1.2.3-70-g09d2