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

feat(performance): getRectByTaro 方法在小程序内增加缓存以提升性能 #2831

Open
wants to merge 6 commits into
base: next
Choose a base branch
from

Conversation

522109452
Copy link
Contributor

@522109452 522109452 commented Dec 5, 2024

🤔 这个变动的性质是?

  • 性能优化

🔗 相关 Issue

#2829

💡 需求背景和解决方案

解决 rang组件使用卡顿问题。
getRectByTaro返回时间从 100+ms -> 3ms
当然其他频繁调用 getRectByTaro的场景也会获得提升

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 代码演示已提供或无须提供
  • 文档已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • TypeScript 定义已补充或无须补充
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • 新功能

    • 引入了一个缓存机制以优化矩形检索过程。
    • 新增 MiniLru 类以实现简单的最近最少使用(LRU)缓存机制。
  • 性能改进

    • 通过缓存矩形值,减少了重复计算,提高了效率。

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

此次更改引入了一个缓存机制,使用 MiniLru 库来优化 getRectByTaro 函数。通过创建一个最大容量为 10 的 MiniLru 实例,函数能够存储先前计算的矩形值。当请求矩形时,函数首先检查缓存中是否已有对应的值,如果有,则直接返回缓存结果;如果没有,则执行选择器查询以获取矩形尺寸,并将结果缓存以供将来使用。

Changes

文件路径 更改摘要
src/utils/get-rect-by-taro.ts 引入 MiniLru 库,创建一个最大容量为 10 的缓存实例,修改 getRectByTaro 函数以实现缓存机制。
src/utils/lru.ts 新增 MiniLru 类,实现简单的 LRU 缓存机制,包含 getsethas 方法。

Possibly related PRs

Suggested labels

size/S, 3.x

Suggested reviewers

  • oasis-cloud
  • xiaoyatong

Poem

🐰 在兔子洞里藏着宝,
矩形数据不再烦恼。
小小缓存帮我忙,
取值迅速如飞翔。
感谢代码的智慧光,
让我们一起乐无疆! 🌟


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.

@github-actions github-actions bot added the 2.x label Dec 5, 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

🧹 Outside diff range and nitpick comments (1)
src/utils/get-rect-by-taro.ts (1)

2-2: 缓存实现需要考虑以下几个方面

  1. 缓存大小限制为10项可能不够用,建议根据实际使用场景进行调整
  2. 建议添加缓存失效机制,避免在元素位置变化时返回过期数据

建议考虑以下几点优化:

  • 根据性能分析确定合适的缓存大小
  • 添加缓存过期时间或在元素位置变化时清除缓存
  • 考虑在组件卸载时清理相关缓存

Also applies to: 5-5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 402e32f and f33e4e9.

📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/utils/get-rect-by-taro.ts (2 hunks)
🔇 Additional comments (2)
src/utils/get-rect-by-taro.ts (1)

36-45: 验证缓存对性能的影响

需要验证缓存实现是否达到预期的性能提升(从100ms降至3ms)。

✅ Verification successful

Based on the search results, I can now generate the final response since I have enough information about the usage patterns of getRectByTaro:

缓存策略合理,无需额外性能验证

经过分析,getRectByTaro 主要用于以下场景:

  • 组件初始化时获取元素尺寸(如 Swipe、Picker、Sticky 等)
  • 响应用户交互时的动态测量(如 Range、Drag 组件)

这些使用场景都是低频操作,现有的 LRU 缓存足以应对:

  • 大多数调用发生在组件初始化或用户交互时
  • 没有发现高频重复调用的情况
  • 缓存命中可以避免重复的 DOM 查询开销
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 搜索getRectByTaro的使用场景,评估缓存大小是否合适

# 查找所有调用getRectByTaro的地方
rg -A 3 "getRectByTaro"

# 检查是否有频繁调用的场景
ast-grep --pattern 'getRectByTaro($_)'

Length of output: 14025

package.json (1)

108-109: 依赖添加建议

  1. quick-lru 是一个轻量级库,对打包大小影响较小
  2. 4.0.1 版本较为稳定,但建议定期检查更新以获取安全修复

src/utils/get-rect-by-taro.ts Outdated Show resolved Hide resolved
package.json Outdated Show resolved Hide resolved
@oasis-cloud
Copy link
Collaborator

尝试用更精简的办法实现缓存,不要轻易引入第三方库。

@pull-request-size pull-request-size bot added size/M and removed size/S labels Dec 5, 2024
Copy link

codecov bot commented Dec 5, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.01%. Comparing base (601b5d1) to head (38ec6db).

Additional details and impacted files
@@           Coverage Diff           @@
##             next    #2831   +/-   ##
=======================================
  Coverage   84.01%   84.01%           
=======================================
  Files         219      219           
  Lines       17899    17899           
  Branches     2622     2622           
=======================================
  Hits        15038    15038           
  Misses       2856     2856           
  Partials        5        5           

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

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

🧹 Outside diff range and nitpick comments (3)
src/utils/lru.ts (3)

1-4: 建议改进类型定义以增强类型安全性

建议通过以下方式增强类型安全:

  1. 将类实现为泛型类,以支持不同类型的值
  2. 添加接口定义以明确类的公共 API
-export default class MiniLru {
-  private cache: Map<string, any>
+interface ILruCache<T> {
+  get(key: string): T | null;
+  set(key: string, value: T): void;
+  has(key: string): boolean;
+}
+
+export default class MiniLru<T> implements ILruCache<T> {
+  private cache: Map<string, T>

11-19: 建议优化获取操作的性能

当前实现在更新项目位置时需要两次操作(删除和设置)。考虑使用以下方式优化:

  1. 只在确实需要维护顺序时才执行移动操作
  2. 考虑批量操作场景下的性能优化
 get(key: string): any | null {
   if (this.cache.has(key)) {
     const value = this.cache.get(key)
-    this.cache.delete(key)
-    this.cache.set(key, value)
+    // 仅在需要维护严格顺序时启用以下代码
+    // this.cache.delete(key)
+    // this.cache.set(key, value)
     return value
   }
   return null
 }

1-33: 建议增加监控和内存管理功能

作为在小程序环境中使用的缓存实现,建议考虑:

  1. 添加缓存命中率监控
  2. 实现手动清理缓存的方法
  3. 添加缓存过期机制
  4. 考虑内存使用限制

这些功能将有助于在生产环境中更好地管理和监控缓存性能。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 59fa40d and 0f6a55c.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • src/utils/get-rect-by-taro.ts (2 hunks)
  • src/utils/lru.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/get-rect-by-taro.ts
🔇 Additional comments (1)
src/utils/lru.ts (1)

30-32: 实现正确且简洁

has 方法的实现直接且有效地封装了 Map 的原生功能。

src/utils/lru.ts Outdated Show resolved Hide resolved
src/utils/lru.ts Outdated
Comment on lines 21 to 28
set(key: string, value: any): void {
if (this.cache.has(key)) {
this.cache.delete(key)
} else if (this.cache.size >= this.capacity) {
this.cache.delete(this.cache.keys().next().value as string)
}
this.cache.set(key, value)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议改进设置方法的实现

当前实现存在以下可改进点:

  1. 获取最旧项的方式可以更明确
  2. 缺少对值的类型检查
  3. 建议添加值的验证逻辑
-  set(key: string, value: any): void {
+  set(key: string, value: T): void {
+    if (value === undefined || value === null) {
+      throw new Error('Cache value cannot be null or undefined');
+    }
     if (this.cache.has(key)) {
       this.cache.delete(key)
     } else if (this.cache.size >= this.capacity) {
-      this.cache.delete(this.cache.keys().next().value as string)
+      const oldestKey = Array.from(this.cache.keys())[0];
+      this.cache.delete(oldestKey)
     }
     this.cache.set(key, value)
   }
📝 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
set(key: string, value: any): void {
if (this.cache.has(key)) {
this.cache.delete(key)
} else if (this.cache.size >= this.capacity) {
this.cache.delete(this.cache.keys().next().value as string)
}
this.cache.set(key, value)
}
set(key: string, value: T): void {
if (value === undefined || value === null) {
throw new Error('Cache value cannot be null or undefined');
}
if (this.cache.has(key)) {
this.cache.delete(key)
} else if (this.cache.size >= this.capacity) {
const oldestKey = Array.from(this.cache.keys())[0];
this.cache.delete(oldestKey)
}
this.cache.set(key, value)
}

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

🧹 Outside diff range and nitpick comments (2)
src/utils/lru.ts (2)

14-22: 建议优化获取操作的性能

当前实现中,获取缓存项时执行了多余的删除和重新设置操作。可以使用 Map 的内置方法来优化性能。

 get(key: any): any | null {
   if (this.cache.has(key)) {
     const value = this.cache.get(key)
-    this.cache.delete(key)
-    this.cache.set(key, value)
+    // 使用 Map 的 set 方法自动更新项的位置
+    this.cache.set(key, value)
     return value
   }
   return null
 }

1-36: 建议考虑添加额外的缓存特性

当前实现是一个基础的 LRU 缓存,建议考虑添加以下特性以增强其在生产环境中的实用性:

  1. TTL(存活时间)支持
  2. 最大内存限制
  3. 缓存统计(命中率、未命中率等)
  4. 缓存清理策略配置
  5. 序列化/反序列化支持
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f6a55c and 91e4a78.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • src/utils/lru.ts (1 hunks)
🔇 Additional comments (3)
src/utils/lru.ts (3)

6-12: 构造函数实现正确

构造函数包含了适当的容量验证,实现逻辑清晰。


33-35: has 方法实现正确

方法实现简洁明了,直接使用 Map 的内置方法。


24-31: 🛠️ Refactor suggestion

建议优化设置方法并添加值验证

当前实现在获取最旧项和值验证方面可以改进:

  1. 使用更高效的方式获取最旧项
  2. 添加值的验证逻辑
-  set(key: any, value: any): void {
+  set(key: K, value: V): void {
+    if (value === undefined || value === null) {
+      throw new Error('缓存值不能为 null 或 undefined');
+    }
     if (this.cache.has(key)) {
       this.cache.delete(key)
     } else if (this.cache.size >= this.capacity) {
-      this.cache.delete(this.cache.keys().next().value)
+      const oldestKey = Array.from(this.cache.keys())[0];
+      this.cache.delete(oldestKey)
     }
     this.cache.set(key, value)
   }

Likely invalid or redundant comment.

Comment on lines +1 to +4
export default class MiniLru {
private cache: Map<any, any>

private capacity: number
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议使用泛型来增强类型安全性

当前实现使用 any 类型可能导致运行时类型错误。建议改用泛型来提供更好的类型安全性。

-export default class MiniLru {
-  private cache: Map<any, any>
+export default class MiniLru<K, V> {
+  private cache: Map<K, V>
📝 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
export default class MiniLru {
private cache: Map<any, any>
private capacity: number
export default class MiniLru<K, V> {
private cache: Map<K, V>
private capacity: number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants