-
Notifications
You must be signed in to change notification settings - Fork 4
⚡ Bolt: Optimize Context lookups to avoid double-lookups and unnecessary .clone()s
#39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ashyanSpada
wants to merge
3
commits into
master
Choose a base branch
from
bolt-optimize-context-lookups-8345709712832303084
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| ## 2024-03-24 - Avoiding Double Hash Map Lookups and Redundant Locks | ||
|
|
||
| **Learning:** `ContextValue` variant implementations within global or shared scope state access via `std::collections::HashMap` behind a `std::sync::Mutex` can incur non-trivial performance costs when lookups are chained directly after checking presence, and when the value structure forces redundant inner cloning inside loops or repeated tree accesses (as in AST execution). Even though `Arc::clone` is fast, `Value::clone` could allocate depending on its variants (e.g., recursive data structures such as lists and maps). In highly repetitive parsing/execution cycles like `execute_expression`, saving redundant lookups and unneeded clones measurably reduces baseline execution time (around 3-5%). | ||
|
|
||
| **Action:** Whenever retrieving an option from a synchronized shared state (like `Mutex<HashMap>`), directly lock, grab `.cloned()` or take ownership of the inner value via single lookup in match block to reduce critical section duration and avoid expensive intermediate value duplications. Ensure `HashMap::get()` is used correctly by directly evaluating the Option it returns, instead of first running `.is_none()` and then repeating the `get` call. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| --- src/context.rs | ||
| +++ src/context.rs | ||
| @@ -32,32 +32,31 @@ | ||
| } | ||
|
|
||
| pub fn get_func(&self, name: &str) -> Option<Arc<InnerFunction>> { | ||
| + // ⚡ Bolt Optimization: Avoid unnecessary `.clone()` on the inner function | ||
| + // by directly taking ownership of the value returned by `get()` | ||
| let value = self.get(name)?; | ||
| match value { | ||
| ContextValue::Function(func) => Some(func), | ||
| ContextValue::Variable(_) => None, | ||
| } | ||
| } | ||
|
|
||
| pub fn get_variable(&self, name: &str) -> Option<Value> { | ||
| + // ⚡ Bolt Optimization: Avoid unnecessary `.clone()` on the inner variable | ||
| + // by directly taking ownership of the value returned by `get()` | ||
| let value = self.get(name)?; | ||
| match value { | ||
| ContextValue::Variable(v) => Some(v), | ||
| ContextValue::Function(_) => None, | ||
| } | ||
| } | ||
|
|
||
| pub fn get(&self, name: &str) -> Option<ContextValue> { | ||
| - let binding = self.0.lock().unwrap(); | ||
| - let value = binding.get(name)?; | ||
| - Some(value.clone()) | ||
| + // ⚡ Bolt Optimization: Minimize lock duration and avoid multi-step lookups | ||
| + self.0.lock().unwrap().get(name).cloned() | ||
| } | ||
|
|
||
| pub fn value(&self, name: &str) -> Result<Value> { | ||
| - let binding = self.0.lock().unwrap(); | ||
| - if binding.get(name).is_none() { | ||
| - return Ok(Value::None); | ||
| - } | ||
| - let value = binding.get(name).unwrap(); | ||
| + // ⚡ Bolt Optimization: Avoid double map lookups (no `is_none()` followed by `unwrap()`) | ||
| + let value = self.get(name); | ||
| match value { | ||
| Some(ContextValue::Variable(v)) => Ok(v), | ||
| Some(ContextValue::Function(func)) => func(Vec::new()), | ||
| None => Ok(Value::None), | ||
| } | ||
| } | ||
| } | ||
| @@ -102,4 +101,23 @@ | ||
| $crate::create_context!((&mut ctx) $($tt)*); | ||
| ctx | ||
| }}; | ||
| } | ||
| + | ||
| +#[cfg(test)] | ||
| +mod tests { | ||
| + use super::*; | ||
| + | ||
| + #[test] | ||
| + fn test_context_lookups() { | ||
| + let mut ctx = Context::new(); | ||
| + ctx.set_variable("a", Value::from(1)); | ||
| + ctx.set_func("b", Arc::new(|_| Ok(Value::from(2)))); | ||
| + | ||
| + assert_eq!(ctx.get_variable("a"), Some(Value::from(1))); | ||
| + assert_eq!(ctx.get_variable("b"), None); | ||
| + assert!(ctx.get_func("b").is_some()); | ||
| + assert!(ctx.get_func("a").is_none()); | ||
| + | ||
| + assert_eq!(ctx.value("a").unwrap(), Value::from(1)); | ||
| + assert_eq!(ctx.value("b").unwrap(), Value::from(2)); | ||
| + assert_eq!(ctx.value("c").unwrap(), Value::None); | ||
| + } | ||
| +} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,36 +31,37 @@ impl Context { | |
| } | ||
|
|
||
| pub fn get_func(&self, name: &str) -> Option<Arc<InnerFunction>> { | ||
| // ⚡ Bolt Optimization: Avoid unnecessary `.clone()` on the inner function | ||
| // by directly taking ownership of the value returned by `get()` | ||
| let value = self.get(name)?; | ||
| match value { | ||
| ContextValue::Function(func) => Some(func.clone()), | ||
| ContextValue::Function(func) => Some(func), | ||
| ContextValue::Variable(_) => None, | ||
| } | ||
| } | ||
|
|
||
| pub fn get_variable(&self, name: &str) -> Option<Value> { | ||
| // ⚡ Bolt Optimization: Avoid unnecessary `.clone()` on the inner variable | ||
| // by directly taking ownership of the value returned by `get()` | ||
| let value = self.get(name)?; | ||
| match value { | ||
| ContextValue::Variable(v) => Some(v.clone()), | ||
| ContextValue::Variable(v) => Some(v), | ||
| ContextValue::Function(_) => None, | ||
| } | ||
|
Comment on lines
46
to
50
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| } | ||
|
|
||
| pub fn get(&self, name: &str) -> Option<ContextValue> { | ||
| let binding = self.0.lock().unwrap(); | ||
| let value = binding.get(name)?; | ||
| Some(value.clone()) | ||
| // ⚡ Bolt Optimization: Minimize lock duration and avoid multi-step lookups | ||
| self.0.lock().unwrap().get(name).cloned() | ||
| } | ||
|
|
||
| pub fn value(&self, name: &str) -> Result<Value> { | ||
| let binding = self.0.lock().unwrap(); | ||
| if binding.get(name).is_none() { | ||
| return Ok(Value::None); | ||
| } | ||
| let value = binding.get(name).unwrap(); | ||
| // ⚡ Bolt Optimization: Avoid double map lookups (no `is_none()` followed by `unwrap()`) | ||
| let value = self.get(name); | ||
| match value { | ||
| ContextValue::Variable(v) => Ok(v.clone()), | ||
| ContextValue::Function(func) => func(Vec::new()), | ||
| Some(ContextValue::Variable(v)) => Ok(v), | ||
| Some(ContextValue::Function(func)) => func(Vec::new()), | ||
| None => Ok(Value::None), | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -104,3 +105,24 @@ macro_rules! create_context { | |
| ctx | ||
| }}; | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn test_context_lookups() { | ||
| let mut ctx = Context::new(); | ||
| ctx.set_variable("a", Value::from(1)); | ||
| ctx.set_func("b", Arc::new(|_| Ok(Value::from(2)))); | ||
|
|
||
| assert_eq!(ctx.get_variable("a"), Some(Value::from(1))); | ||
| assert_eq!(ctx.get_variable("b"), None); | ||
| assert!(ctx.get_func("b").is_some()); | ||
| assert!(ctx.get_func("a").is_none()); | ||
|
|
||
| assert_eq!(ctx.value("a").unwrap(), Value::from(1)); | ||
| assert_eq!(ctx.value("b").unwrap(), Value::from(2)); | ||
| assert_eq!(ctx.value("c").unwrap(), Value::None); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| use crate::define::Result; | ||
| use crate::function::InnerFunction; | ||
| use crate::value::Value; | ||
| use core::clone::Clone; | ||
| use std::collections::HashMap; | ||
| use std::sync::{Arc, Mutex}; | ||
|
|
||
| #[derive(Clone)] | ||
| pub enum ContextValue { | ||
| Variable(Value), | ||
| Function(Arc<InnerFunction>), | ||
| } | ||
|
|
||
| pub struct Context(pub Arc<Mutex<HashMap<String, ContextValue>>>); | ||
|
|
||
| impl Context { | ||
| pub fn new() -> Self { | ||
| Context(Arc::new(Mutex::new(HashMap::new()))) | ||
| } | ||
|
|
||
| pub fn set_func(&mut self, name: &str, func: Arc<InnerFunction>) { | ||
| self.set(name, ContextValue::Function(func.clone())); | ||
| } | ||
|
|
||
| pub fn set_variable(&mut self, name: &str, value: Value) { | ||
| self.set(name, ContextValue::Variable(value)); | ||
| } | ||
|
|
||
| pub fn set(&mut self, name: &str, v: ContextValue) { | ||
| self.0.lock().unwrap().insert(name.to_string(), v); | ||
| } | ||
|
|
||
| pub fn get_func(&self, name: &str) -> Option<Arc<InnerFunction>> { | ||
| // ⚡ Bolt Optimization: Avoid unnecessary `.clone()` on the inner function | ||
| // by directly taking ownership of the value returned by `get()` | ||
| let value = self.get(name)?; | ||
| match value { | ||
| ContextValue::Function(func) => Some(func), | ||
| ContextValue::Variable(_) => None, | ||
| } | ||
| } | ||
|
|
||
| pub fn get_variable(&self, name: &str) -> Option<Value> { | ||
| // ⚡ Bolt Optimization: Avoid unnecessary `.clone()` on the inner variable | ||
| // by directly taking ownership of the value returned by `get()` | ||
| let value = self.get(name)?; | ||
| match value { | ||
| ContextValue::Variable(v) => Some(v), | ||
| ContextValue::Function(_) => None, | ||
| } | ||
| } | ||
|
|
||
| pub fn get(&self, name: &str) -> Option<ContextValue> { | ||
| // ⚡ Bolt Optimization: Minimize lock duration and avoid multi-step lookups | ||
| self.0.lock().unwrap().get(name).cloned() | ||
| } | ||
|
|
||
| pub fn value(&self, name: &str) -> Result<Value> { | ||
| // ⚡ Bolt Optimization: Avoid double map lookups (no `is_none()` followed by `unwrap()`) | ||
| let value = self.get(name); | ||
| match value { | ||
| Some(ContextValue::Variable(v)) => Ok(v), | ||
| Some(ContextValue::Function(func)) => func(Vec::new()), | ||
| None => Ok(Value::None), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// | ||
| ///```rust | ||
| /// use expression_engine::create_context; | ||
| /// use expression_engine::Value; | ||
| /// let a = create_context!("d" => 3.5, "c" => Arc::new(|params| { | ||
| /// Ok(Value::from(3)) | ||
| /// })); | ||
| ///``` | ||
| /// | ||
| /// | ||
| #[macro_export] | ||
| macro_rules! create_context { | ||
| (($ctx:expr) $k:expr => Arc::new($($v:tt)*), $($tt:tt)*) => {{ | ||
| $ctx.set_func($k, Arc::new($($v)*)); | ||
| $crate::create_context!(($ctx) $($tt)*); | ||
| }}; | ||
|
|
||
| (($ctx:expr) $k:expr => $v:expr, $($tt:tt)*) => {{ | ||
| $ctx.set_variable($k, Value::from($v)); | ||
| $crate::create_context!(($ctx) $($tt)*); | ||
| }}; | ||
|
|
||
| (($ctx:expr) $k:expr => Arc::new($($v:tt)*)) => {{ | ||
| $ctx.set_func($k, Arc::new($($v)*)); | ||
| }}; | ||
|
|
||
| (($ctx:expr) $k:expr => $v:expr) => {{ | ||
| $ctx.set_variable($k, Value::from($v)); | ||
| }}; | ||
|
|
||
| (($ctx:expr)) => {}; | ||
|
|
||
| ($($tt:tt)*) => {{ | ||
| use std::sync::Arc; | ||
| let mut ctx = $crate::Context::new(); | ||
| $crate::create_context!((&mut ctx) $($tt)*); | ||
| ctx | ||
| }}; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| --- src/context.rs | ||
| +++ src/context.rs | ||
| @@ -107,4 +107,24 @@ | ||
| $crate::create_context!((&mut ctx) $($tt)*); | ||
| ctx | ||
| }}; | ||
| } | ||
| + | ||
| +#[cfg(test)] | ||
| +mod tests { | ||
| + use super::*; | ||
| + | ||
| + #[test] | ||
| + fn test_context_lookups() { | ||
| + let mut ctx = Context::new(); | ||
| + ctx.set_variable("a", Value::from(1)); | ||
| + ctx.set_func("b", Arc::new(|_| Ok(Value::from(2)))); | ||
| + | ||
| + assert_eq!(ctx.get_variable("a"), Some(Value::from(1))); | ||
| + assert_eq!(ctx.get_variable("b"), None); | ||
| + assert!(ctx.get_func("b").is_some()); | ||
| + assert!(ctx.get_func("a").is_none()); | ||
| + | ||
| + assert_eq!(ctx.value("a").unwrap(), Value::from(1)); | ||
| + assert_eq!(ctx.value("b").unwrap(), Value::from(2)); | ||
| + assert_eq!(ctx.value("c").unwrap(), Value::None); | ||
| + } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For improved conciseness and readability, you can combine the
getcall and thematchstatement. This avoids the intermediatevaluevariable and the use of the?operator, making the logic more direct.