Skip to content

perf: improve useSet operations performance - #2742

Open
DamianKocjan wants to merge 1 commit into
streamich:masterfrom
DamianKocjan:perf-useSet
Open

DamianKocjan wants to merge 1 commit into
streamich:masterfrom
DamianKocjan:perf-useSet

Conversation

@DamianKocjan

Copy link
Copy Markdown

Instead of converting set objects to array and using array methods (O(n)), we utilize direct set methods (O(1))

Description

Optimized useSet operations by replacing intermediate array conversions (O(n)) with native Set methods (O(1)) and avoiding unnecessary re-renders:

  • add: Uses has() (O(1)) to bail out early if the item already exists; otherwise adds via newSet.add() instead of array spread.
  • remove: Uses has() (O(1)) to bail out early if the item is missing; otherwise deletes via newSet.delete() instead of array .filter().
  • toggle: Uses native has(), delete(), and add() directly on the cloned Set in O(1) rather than array filtering/spreading.
  • clear: Checks prevSet.size === 0 to skip re-rendering if already empty.

Note on Storybook: stories/useSet.story.tsx already exists and covers all actions. Since this is an internal performance refactor with no public API changes, is an additional story needed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as before)

Checklist

  • Read the Contributing Guide
  • Perform a code self-review
  • Comment the code, particularly in hard-to-understand areas
  • Add documentation
  • Add hook's story at Storybook
  • Cover changes with tests
  • Ensure the test suite passes (yarn test)
  • Provide 100% tests coverage
  • Make sure code lints (yarn lint). Fix it with yarn lint:fix in case of failure.
  • Make sure types are fine (yarn lint:types).

Instead of converting set objects to array and using array methods (O(n)), we utilize direct set methods (O(1))

This branch has not been deployed

No deployments
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