diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-01-19 20:14:57 +0100 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-01-19 20:14:57 +0100 |
| commit | be37a4ed4059ce79321c5e3f2438934866ec7be5 (patch) | |
| tree | 9ab9ece4b21bd805e614743420896dafe9f794dd /src/function_cache.rs | |
| parent | 1c5233b185e52d42c7878ac8b6cf046a5bb54a09 (diff) | |
add function_cache for performence gain
Diffstat (limited to 'src/function_cache.rs')
| -rw-r--r-- | src/function_cache.rs | 32 |
1 files changed, 32 insertions, 0 deletions
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<Complex, Complex>, +} + +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 + } + } +} |