8000 refactor(watch deep): use bfs instead of dfs by jsy-0526 · Pull Request #13433 · vuejs/core · GitHub
[go: up one dir, main page]

Skip to content

refactor(watch deep): use bfs instead of dfs #13433

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

Closed
wants to merge 1 commit into from
Closed

Conversation

jsy-0526
Copy link
@jsy-0526 jsy-0526 commented Jun 4, 2025

hi, I have refactored the deep implementation logic of the watch api in reactivity. Previously, deep matching was carried out using the dfs method. But this will have the following problems.

  1. If the object is very deep, it may cause a stack overflow
  2. dfs will perform an additional match

Summary by CodeRabbit

  • Refactor
    • Improved performance and reliability of internal data traversal, resulting in more efficient handling of complex or deeply nested data structures. No changes to user-facing functionality.

Copy link
coderabbitai bot commented Jun 4, 2025

Walkthrough

The traverse function in packages/reactivity/src/watch.ts was refactored from a recursive approach to an iterative breadth-first traversal using a queue. The new implementation processes nested structures without recursion, maintaining the same input/output signature and traversal semantics.

Changes

File(s) Change Summary
packages/reactivity/src/watch.ts Refactored the traverse function from recursive to iterative breadth-first traversal using a queue.

Poem

A hop through code, no stack to fear,
The queue now leads us, far and near.
Traversing deep, we loop and peek,
No more recursion, no cycles sneak!
With every breadth, our search is neat—
This bunny’s journey is complete. 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 0

🧹 Nitpick comments (1)
packages/reactivity/src/watch.ts (1)

346-348: Consider performance implications of queue.shift().

Using queue.shift() for dequeuing has O(n) time complexity in JavaScript arrays. For deeply nested objects with many siblings at each level, this could impact performance significantly.

Consider using a more efficient queue implementation:

-  const queue: Array<[any, number]> = []
+  const queue: Array<[any, number]> = []
+  let queueIndex = 0
   
   // ... initialization code ...
   
-  while (queue.length > 0) {
-    const [currentValue, currentDepth] = queue.shift()!
+  while (queueIndex < queue.length) {
+    const [currentValue, currentDepth] = queue[queueIndex++]

This eliminates the O(n) shift operation while maintaining the same FIFO behavior.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e53a4ff and f68d595.

📒 Files selected for processing (1)
  • packages/reactivity/src/watch.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (5)
packages/reactivity/src/watch.ts (5)

336-344: LGTM: Solid initialization and early return logic.

The initialization correctly handles the seen parameter for backward compatibility and implements proper early returns for non-traversable values.


361-366: LGTM: Proper cycle detection implementation.

The seen set check correctly prevents infinite loops with circular references, and adding to the seen set at the right time maintains the same semantics as the original recursive implementation.


372-391: Excellent comprehensive child enumeration logic.

The implementation correctly handles all supported object types (refs, arrays, sets, maps, plain objects) and properly includes enumerable symbol properties. The depth propagation logic is sound.


331-395: Successful refactoring that achieves the stated objectives.

This BFS implementation effectively addresses the original concerns:

  • ✅ Eliminates stack overflow risk for deeply nested objects
  • ✅ Maintains identical traversal semantics
  • ✅ Preserves function signature for backward compatibility
  • ✅ Includes clear, documented logic flow

The refactoring successfully transforms a recursive DFS approach into an iterative BFS approach while maintaining all the original functionality. The only minor consideration is the queue.shift() performance, but this is acceptable for typical use cases.


352-358:

✅ Verification successful

Verify depth handling correctness for edge cases.

The depth check logic appears correct, but let's ensure it handles the edge case where currentDepth === 0 properly.


🏁 Script executed:

#!/bin/bash
# Description: Verify that the traverse function is used correctly in the codebase and check for any existing tests
# Expected: Find usages and tests that validate depth behavior

# Search for traverse function usage
rg -A 5 'traverse\(' --type ts

# Look for existing tests
fd -e spec.ts -e test.ts | xargs rg -l 'traverse'

Length of output: 2078


🏁 Script executed:

#!/bin/bash
# Show traverse implementation context
rg -C 20 -n "export function traverse" packages/reactivity/src/watch.ts

# Show usages of traverse with explicit depth
rg -C 10 -n "traverse(source" packages/reactivity/src/watch.ts

Length of output: 1429


🏁 Script executed:

#!/bin/bash
# Extract the full traverse function for detailed review
sed -n '331,430p' packages/reactivity/src/watch.ts

Length of output: 2046


Depth checks for zero-depth cases are correctly handled

The early‐return if (depth <= 0 …) return value ensures that calling traverse(obj, 0) skips all property reads, and the in‐loop guard if (currentDepth <= 0 …) continue prevents exploring children once their depth counter hits zero. No changes needed here.

@@ -333,35 +333,63 @@ export function traverse(
depth: number = Infinity,
seen?: Set<unknown>,
Copy link
Member

Choose a reason for hiding this comment

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

It seems that seen is no longer needed here.

queue.push([value, depth])

while (queue.length > 0) {
const [currentValue, currentDepth] = queue.shift()!
Copy link
Member

Choose a reason for hiding this comment

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

The time complexity of queue.shift() is O(n), so it can be optimized by tracking the index manually:

const queue: Array<[any, number]> = []
let queueIndex = 0

const [currentValue, currentDepth] = queue[queueIndex++]

Copy link
Author

Choose a reason for hiding this comment

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

yep,you are right!

@edison1105
Copy link
Member

see https://github.com/vuejs/core/blob/main/.github/contributing.md

Code refactors are only accepted if it improves performance, or comes with sufficient explanations on why it objectively improves the code quality (e.g. makes a related feature implementation easier).

Thanks for your contribution. Could you provide a benchmark?

Comment on lines +336 to +337
const activeSeen = seen || new Set()
const queue: Array<[any, number]> = []

Choose a reason for hiding this comment

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

Copy link
Author

Choose a reason for hiding this comment

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

yes , you are right。 I will move these two lines to the bottom

@skirtles-code
Copy link 8000
Contributor

I know the Playground isn't a particularly reliable way to do benchmarks, but from a quick bit of experimenting it looks like this PR may have a significantly adverse affect on performance:

Maybe that can be improved with further tweaks, but I suspect the data structures required to implement a BFS may place limits on how fast it can be.

@jsy-0526
Copy link
Author
jsy-0526 commented Jun 5, 2025

Thank you for your reply. I tried these two demos. What you said is right. I investigated the reason because the Array.shift method was constantly used in my code. This is a waste of performance. I modified it and tested it. The performances of the two were about the same. So I think the improvement in performance brought by this pr is not obvious.

@jsy-0526
Copy link
Author
jsy-0526 commented Jun 5, 2025

see https://github.com/vuejs/core/blob/main/.github/contributing.md

Code refactors are only accepted if it improves performance, or comes with sufficient explanations on why it objectively improves the code quality (e.g. makes a related feature implementation easier).

Thanks for your contribution. Could you provide a benchmark?

Thank you for your reply. After the benchmark test. The performance before and after the modification is almost the same, and it belongs to extreme scenarios. So I think the improvement in performance brought by this pr is not obvious.

@edison1105
Copy link
Member

see benchmark

image

@skirtles-code
Copy link
Contributor

@jsy-0526 Please push your latest changes to the PR so we can see them.

@jsy-0526 jsy-0526 closed this Jun 6, 2025
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.

5 participants
0