Skip to content
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

chore(currency): search by ID from Map #1465

Merged
merged 4 commits into from
Oct 4, 2024

Conversation

kevindavee
Copy link
Contributor

@kevindavee kevindavee commented Oct 3, 2024

Description of the changes

Search currency with .fromId results from a Map.
Since Node.js is a single thread, we couldn't loop through an array in parallel.

const data: { currency: string } = [...]; // Consist of 200 items

await Promise.all(data.map(item) => {
   // do some async task // takes 10ms

  const currency = currencyManager.fromId(item.currency) // takes 20ms
  
  return result;
});

In the above example, even though we use Promise.all, the whole operation will take (200* 20ms) + 10ms = 4010ms. The async task could be executed concurrently, but the array iteration runs serially. If we cache the result in a Map, we could get the data with O(1) time complexity.

Summary by CodeRabbit

  • New Features
    • Improved currency retrieval efficiency through caching in the CurrencyManager.
  • Tests
    • Added tests to ensure correct retrieval of currencies by ID, confirming caching functionality.

Copy link

coderabbitai bot commented Oct 3, 2024

Walkthrough

The changes introduce a new private property, knownCurrenciesById, in the CurrencyManager class to cache CurrencyDefinition objects by their IDs, optimizing the retrieval process. The fromId method is updated to first check this cache before searching the knownCurrencies array. Additionally, a new test case is added to verify the functionality of the fromId method, ensuring it correctly retrieves a specific token by its ID and validating the caching mechanism.

Changes

File Change Summary
packages/currency/src/currencyManager.ts Added a private property knownCurrenciesById to cache CurrencyDefinition objects by ID. Modified fromId method to utilize this cache for improved retrieval efficiency.
packages/currency/test/currencyManager.test.ts Added a test case in the Accessing currencies section to verify retrieval of a token by ID, ensuring correct properties and testing the caching mechanism.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CurrencyManager
    participant Cache

    Client->>CurrencyManager: fromId("USDC-multichain-moonbeam")
    CurrencyManager->>Cache: Check knownCurrenciesById
    alt Currency found in cache
        Cache-->>CurrencyManager: Return CurrencyDefinition
        CurrencyManager-->>Client: Return CurrencyDefinition
    else Currency not found
        CurrencyManager->>CurrencyManager: Search knownCurrencies
        CurrencyManager->>Cache: Cache CurrencyDefinition
        CurrencyManager-->>Client: Return CurrencyDefinition
    end
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 796baba and 7f95092.

📒 Files selected for processing (2)
  • packages/currency/src/currencyManager.ts (2 hunks)
  • packages/currency/test/currencyManager.test.ts (1 hunks)
🔇 Additional comments (1)
packages/currency/src/currencyManager.ts (1)

23-25: Implementation of caching mechanism looks good

The addition of knownCurrenciesById Map initializes correctly.

packages/currency/test/currencyManager.test.ts Outdated Show resolved Hide resolved
packages/currency/src/currencyManager.ts Outdated Show resolved Hide resolved
@kevindavee kevindavee changed the title chore(currency): cache .fromId result chore(currency): search by ID from Map Oct 3, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 7f95092 and 282a30b.

📒 Files selected for processing (2)
  • packages/currency/src/currencyManager.ts (3 hunks)
  • packages/currency/test/currencyManager.test.ts (1 hunks)
🔇 Additional comments (5)
packages/currency/src/currencyManager.ts (4)

23-24: LGTM: New property for caching currency definitions

The addition of the knownCurrenciesById property as a Map is a good choice for caching currency definitions by their IDs. This will allow for O(1) lookup time, addressing the performance issue mentioned in the PR objectives.


47-49: LGTM: Efficient initialization of knownCurrenciesById

The initialization of knownCurrenciesById in the constructor is implemented efficiently, using a single pass over knownCurrencies. This approach ensures that the cache is fully populated at construction time, providing immediate O(1) lookups for all known currencies. This change effectively addresses the suggestion from the past review comment.


93-93: LGTM: Optimized fromId method for O(1) lookup

The fromId method has been simplified to directly use the knownCurrenciesById Map, resulting in O(1) lookup time. This change significantly improves the method's performance, especially when handling multiple currency lookups, as mentioned in the PR objectives. The elimination of the fallback linear search is appropriate since the cache is now pre-populated in the constructor.


23-24: LGTM: Effective implementation of caching for improved performance

The changes introduced in this PR successfully implement a caching mechanism for currency definitions using a Map. The cache is efficiently populated at construction time and utilized in the fromId method, resulting in O(1) lookup time for currency definitions. These modifications effectively address the performance issue described in the PR objectives, particularly for scenarios involving multiple currency lookups.

The implementation is well-structured, maintains the integrity of the CurrencyManager class, and addresses the suggestions from the past review comment. Overall, these changes should significantly improve the efficiency of currency-related operations in the system.

Also applies to: 47-49, 93-93

packages/currency/test/currencyManager.test.ts (1)

156-161: Good addition to the test suite.

This new test case enhances the coverage of the fromId method and aligns well with the PR objectives of implementing caching for the .fromId results. It integrates seamlessly into the existing test structure without disrupting other tests.

As the caching functionality evolves, consider adding more comprehensive tests for various caching scenarios, such as cache expiration (if implemented) or cache invalidation.

@MantisClone
Copy link
Member

Reviewing... 🚧

@kevindavee kevindavee merged commit f2667d0 into master Oct 4, 2024
25 checks passed
@kevindavee kevindavee deleted the chore/cache-find-currency-from-id-result branch October 4, 2024 03:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants