perf: Optimize BTree search using binary search #767
Merged
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.
Description
This pull request optimizes the search function in the BTree implementation by replacing the linear search with a binary search algorithm. This change significantly improves the search performance, especially for large trees, without altering the existing functionality.
The optimization is achieved by modifying the
search
method in theBTree
struct to use thebinary_search
method on thekeys
vector instead of a while loop. This change reduces the time complexity of searching within a node from O(n) to O(log n), where n is the number of keys in the node.Type of change
Implementation Details
The main changes are in the
search
method of theBTree
struct:binary_search
method on thekeys
vector.Benchmark Results
Environment: MacOS 14.5, Apple M1 Pro, 32 GB RAM
Dataset: 1,000,000 random integers for insertion, 1,000,000 searches for the key 500,000
Before optimization:
After optimization:
Note: Insertion time remains largely unchanged, as expected.
Checklist:
cargo clippy --all -- -D warnings
just before my last commit and fixed any issue that was found.cargo fmt
just before my last commit.cargo test
just before my last commit and all tests passed.CONTRIBUTING.md
and my code follows its guidelines.All existing tests pass with the new implementation. No new tests were added as the existing ones adequately cover the modified functionality.