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

Perf: Cache styles to avoid creating new object style every execution #250

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

sunrise1002
Copy link

@sunrise1002 sunrise1002 commented Jul 18, 2024

On every render, the flatten method will be executed, returning the appropriate styles from StyleSheet.flatten. However, StyleSheet.flatten creates and returns a new object on each execution, as seen here:
https://github.com/facebook/react-native/blob/8408b8bc96db15e265ca65fce7875ee65dcfdcec/packages/react-native/Libraries/StyleSheet/flattenStyle.js#L29

To avoid this, we can cache the created styles and reuse them if the same style is needed again. This approach provides the same benefits as using StyleSheet.create or declaring a styles object outside of the render method.

Summary by CodeRabbit

  • Refactor
    • Improved style handling and caching mechanism for more efficient and consistent styling in the mobile app.

Copy link

coderabbitai bot commented Jul 18, 2024

Walkthrough

The StyleBuilder class in builder.ts has been enhanced to construct styles based on sorted definitions, ensuring consistent key generation. It now merges styles efficiently into an object, improving handling and caching. This update optimizes style management and retrieval.

Changes

File Change Summary
packages/mobile/src/styles/builder/builder.ts Enhanced StyleBuilder class to use sorted definitions for consistent key generation, and merge styles into an object for improved caching and handling.

Poem

In the realm where codes align,
StyleBuilder dances, oh so fine.
Definitions sorted, keys in sync,
Merging styles faster than you think.
Caching treasures in its chest,
Building styles with utmost zest.
🌟✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a1e84f9 and fc5e523.

Files selected for processing (1)
  • packages/mobile/src/styles/builder/builder.ts (1 hunks)
Additional comments not posted (7)
packages/mobile/src/styles/builder/builder.ts (7)

180-180: Sorting definitions improves cache consistency.

Sorting the definitions ensures that the order of input doesn't affect the cache key, leading to consistent key generation.


182-185: Key generation logic is sound.

The key generation logic concatenates sorted definitions into a single string, which is used as the cache key. This approach is effective for ensuring unique keys for different style combinations.


186-187: Check for existing cached styles.

The code checks if the styles are already cached using the generated key. If found, it returns the cached styles, improving performance by avoiding redundant calculations.


190-193: Merge base definitions into styles.

The loop merges base definitions into the styles object. Ensure that the get method returns valid style objects.


197-200: Merge conditional definitions into styles.

The loop merges conditional definitions into the styles object if they are not null, undefined, or true. Ensure that the get method handles these cases correctly.


204-204: Cache the computed styles.

The computed styles are cached using the generated key, ensuring that future requests for the same styles are served from the cache.


205-205: Return the computed styles.

The method returns the computed styles, either from the cache or newly computed.

Comment on lines +176 to +179
const allDefinitions = [
...(definitions || []),
...(conditionalDefinitions || []),
].filter((definition) => typeof definition === "string");
Copy link

Choose a reason for hiding this comment

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

Ensure definitions are not null or undefined.

The code concatenates definitions and conditionalDefinitions and filters out non-string values. Ensure that definitions and conditionalDefinitions are not null or undefined before concatenation.

-    const allDefinitions = [
-      ...(definitions || []),
-      ...(conditionalDefinitions || []),
-    ].filter((definition) => typeof definition === "string");
+    const allDefinitions = [
+      ...(definitions ?? []),
+      ...(conditionalDefinitions ?? []),
+    ].filter((definition) => typeof definition === "string");
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const allDefinitions = [
...(definitions || []),
...(conditionalDefinitions || []),
].filter((definition) => typeof definition === "string");
const allDefinitions = [
...(definitions ?? []),
...(conditionalDefinitions ?? []),
].filter((definition) => typeof definition === "string");

);
let styles = this.cached.get(keyStyle);
if (styles) return styles;

Copy link

Choose a reason for hiding this comment

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

Ensure styles initialization.

Before merging styles, ensure that the styles variable is properly initialized.

-    let styles = this.cached.get(keyStyle);
-    if (styles) return styles;
+    let styles = this.cached.get(keyStyle) || {};
+    if (Object.keys(styles).length > 0) return styles;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let styles = this.cached.get(keyStyle) || {};
if (Object.keys(styles).length > 0) return styles;

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.

1 participant