Skip to content

perf: cache selector query#49

Merged
danielroe merged 1 commit into
danielroe:mainfrom
alan-agius4:selector-query-cache
Nov 24, 2024
Merged

perf: cache selector query#49
danielroe merged 1 commit into
danielroe:mainfrom
alan-agius4:selector-query-cache

Conversation

@alan-agius4
Copy link
Copy Markdown
Collaborator

@alan-agius4 alan-agius4 commented Nov 22, 2024

This operation is quite repetitive and intensive. However, it can be optimized through caching, as stylesheets rarely change between executions, and selectors are consistently evaluated in the same way.

Description by Callstackai

This PR introduces a caching mechanism for selector tokens to optimize the performance of querying nodes, along with a bug fix for a typo in the attribute setting functionality.

Diagrams of code changes
sequenceDiagram
    participant Client
    participant cachedQuerySelector
    participant selectorTokensCache
    participant parseRelevantSelectors
    participant selectorParser

    Client->>cachedQuerySelector: query(selector, node)
    cachedQuerySelector->>selectorTokensCache: get(selector)
    
    alt Cache Miss
        selectorTokensCache-->>cachedQuerySelector: undefined
        cachedQuerySelector->>parseRelevantSelectors: parseRelevantSelectors(selector)
        parseRelevantSelectors->>selectorParser: parse(selector)
        selectorParser-->>parseRelevantSelectors: tokens
        parseRelevantSelectors-->>cachedQuerySelector: relevantTokens
        cachedQuerySelector->>selectorTokensCache: set(selector, relevantTokens)
    else Cache Hit
        selectorTokensCache-->>cachedQuerySelector: cached tokens
    end

    alt Has Relevant Tokens
        cachedQuerySelector->>cachedQuerySelector: check class/id cache
    else No Relevant Tokens
        cachedQuerySelector->>cachedQuerySelector: fallback to selectOne
    end
    
    cachedQuerySelector-->>Client: result
Loading
Files Changed
FileSummary
packages/beasties/src/dom.tsAdded caching for selector tokens and fixed a typo in the attribute setting.

This PR includes files in programming languages that we currently do not support. We have not reviewed files with the extensions .ts. See list of supported languages.

Summary by CodeRabbit

  • New Features

    • Introduced a caching mechanism for selector tokens, improving the efficiency of querying nodes.
  • Bug Fixes

    • Corrected a typo in the attribute setting functionality to ensure proper operation.

These updates enhance the performance of attribute selector handling within the application.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 22, 2024

Walkthrough

The changes in this pull request primarily involve updates to the packages/beasties/src/dom.ts file, focusing on enhancing attribute selector functionality and implementing a caching mechanism for selector tokens. An import statement was modified to include AttributeSelector, and a typo in the setAttribute method was corrected. A new selectorTokensCache variable was introduced to store parsed selector tokens, optimising the cachedQuerySelector function by checking for cached tokens before parsing, particularly for class and id selectors.

Changes

File Path Change Summary
packages/beasties/src/dom.ts - Updated import statement to include AttributeSelector.
- Fixed typo in setAttribute method from setAttribue to setAttribute.
- Introduced selectorTokensCache variable as a Map for caching selector tokens.
- Modified cachedQuerySelector to leverage the cache for class and id selectors.

Suggested reviewers

  • danielroe

Poem

In the meadow where the selectors play,
A cache was built to save the day.
With attributes now set just right,
Our queries dance in pure delight.
Hopping fast, we leap and bound,
Efficiency in every sound! 🐇✨

Warning

Rate limit exceeded

@alan-agius4 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 47 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a871e1a and 705ca8d.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a871e1a and 705ca8d.

📒 Files selected for processing (1)
  • packages/beasties/src/dom.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/beasties/src/dom.ts

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.

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Nov 22, 2024

CodSpeed Performance Report

Merging #49 will degrade performances by 47.38%

Comparing alan-agius4:selector-query-cache (705ca8d) with main (82523c4)

Summary

❌ 1 regressions
✅ 7 untouched benchmarks

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Benchmarks breakdown

Benchmark main alan-agius4:selector-query-cache Change
run on HTML file 5 ms 9.5 ms -47.38%

Copy link
Copy Markdown

@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: 2

🧹 Outside diff range and nitpick comments (1)
packages/beasties/src/dom.ts (1)

344-345: Typographical errors in TODO comment.

There are typographical errors in the comment; it should read: "We should probably move this cache as part of the class so that it's disposed with it."

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7b382c9 and 405c030.

📒 Files selected for processing (1)
  • packages/beasties/src/dom.ts (3 hunks)
🔇 Additional comments (1)
packages/beasties/src/dom.ts (1)

349-369: Verify thread safety of shared caches in asynchronous contexts.

If cachedQuerySelector is accessed concurrently in an asynchronous environment, using shared caches without proper synchronisation might cause race conditions. Ensure that the caches are either protected against concurrent modifications or that the function is used in a single-threaded context.

Run the following script to check for asynchronous uses of cachedQuerySelector:

Comment thread packages/beasties/src/dom.ts
Comment thread packages/beasties/src/dom.ts
Copy link
Copy Markdown

@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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 405c030 and bd7196f.

📒 Files selected for processing (1)
  • packages/beasties/src/dom.ts (3 hunks)
🔇 Additional comments (2)
packages/beasties/src/dom.ts (2)

21-21: LGTM: Type import addition

The AttributeSelector type import is correctly added and necessary for the new caching implementation.


140-140: LGTM: Proper id setter implementation

The id setter correctly uses setAttribute, maintaining consistency with the className setter implementation.

Comment thread packages/beasties/src/dom.ts
Comment thread packages/beasties/src/dom.ts
@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Nov 22, 2024

Codecov Report

Attention: Patch coverage is 92.30769% with 2 lines in your changes missing coverage. Please review.

Project coverage is 84.74%. Comparing base (82523c4) to head (705ca8d).

Files with missing lines Patch % Lines
packages/beasties/src/dom.ts 92.30% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #49      +/-   ##
==========================================
+ Coverage   84.58%   84.74%   +0.16%     
==========================================
  Files           7        7              
  Lines        1174     1193      +19     
  Branches      273      278       +5     
==========================================
+ Hits          993     1011      +18     
- Misses        181      182       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

@alan-agius4 alan-agius4 force-pushed the selector-query-cache branch 3 times, most recently from 01b7737 to a871e1a Compare November 24, 2024 08:09
This operation is quite repetitive and intensive. However, it can be optimized through caching, as stylesheets rarely change between executions, and selectors are consistently evaluated in the same way.
@danielroe danielroe merged commit cec33d3 into danielroe:main Nov 24, 2024
@alan-agius4 alan-agius4 deleted the selector-query-cache branch November 24, 2024 08:41
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