TheAlgorithms / Rust

All Algorithms implemented in Rust
MIT License
22.91k stars 2.24k forks source link

perf: Optimize BTree search using binary search #767

Closed ie-Yoshisaur closed 3 months ago

ie-Yoshisaur commented 4 months ago

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 the BTree struct to use the binary_search method on the keys 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 the BTree struct:

  1. Replaced the while loop with binary_search method on the keys 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:

All existing tests pass with the new implementation. No new tests were added as the existing ones adequately cover the modified functionality.

codecov-commenter commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 95.08%. Comparing base (65ca19d) to head (b772765).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #767 +/- ## ======================================= Coverage 95.07% 95.08% ======================================= Files 309 309 Lines 22781 22788 +7 ======================================= + Hits 21660 21667 +7 Misses 1121 1121 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

ie-Yoshisaur commented 3 months ago

By the way: would you like to spend some more time with this class?

Of course! I’ll work on fixing that issue and submit a PR soon.