Skip to content

Optimize extendShape #4150

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

Merged
merged 1 commit into from
Apr 16, 2025
Merged

Optimize extendShape #4150

merged 1 commit into from
Apr 16, 2025

Conversation

Andarist
Copy link
Contributor

@Andarist Andarist commented Apr 14, 2025

It has been proposed here and, in fact, it cuts AnswerOverflow/apps/dashboard's instantiations from 13672403 to 3538464 (74% reduction) and check time from 6.5s to 4s (38% reduction).

Summary by CodeRabbit

  • Refactor
    • Improved the efficiency of type-level merging for object shapes, resulting in faster and more direct merging when object keys do not overlap. This change affects only type definitions and does not impact runtime behavior.

Copy link

coderabbitai bot commented Apr 14, 2025

Walkthrough

The changes update two TypeScript utility types, MergeShapes and extendShape, within the objectUtil namespace. Both types now include a conditional check to determine if the key sets of the objects being merged overlap. If there are no overlapping keys, the types are combined using a simple intersection; if there are overlapping keys, the merge uses the original exclusion-based logic. These modifications affect only the type-level behavior and do not alter any runtime code.

Changes

File(s) Change Summary
deno/lib/helpers/util.ts, src/helpers/util.ts Updated MergeShapes and extendShape types in the objectUtil namespace to include a conditional fast path for merging.

Poem

In the warren of types where the helpers reside,
Two shapes now merge with a swifter stride.
If keys don’t collide, they simply unite,
But if there’s a clash, they merge as they might.
Type rabbits rejoice—less hopping around!
For merging is faster when overlaps aren’t found.
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6017b0 and 6a4fdfc.

📒 Files selected for processing (2)
  • deno/lib/helpers/util.ts (2 hunks)
  • src/helpers/util.ts (2 hunks)
🔇 Additional comments (4)
src/helpers/util.ts (2)

100-106: Excellent performance optimization for MergeShapes type!

This optimization introduces a fast path for merging object types when there are no overlapping keys. By using a direct intersection (U & V) in cases where keys don't overlap, the TypeScript compiler can avoid the more complex exclusion-based merging, significantly reducing type instantiations. This aligns with the PR objectives, which report a 74% reduction in instantiations and 38% improvement in type checking time.


138-146: Well-implemented optimization for extendShape type utility

Similar to the MergeShapes optimization, this adds a fast path for cases where object keys don't overlap. The implementation is correct and maintains the same semantics - if keys overlap, it falls back to the original exclusion-based logic. When keys don't overlap, using a simple intersection (A & B) is more efficient and produces equivalent results.

The comment explaining the optimization is clear and helpful for future maintainers.

deno/lib/helpers/util.ts (2)

100-106: Excellent performance optimization for MergeShapes type!

This optimization introduces a fast path for merging object types when there are no overlapping keys. By using a direct intersection (U & V) in cases where keys don't overlap, the TypeScript compiler can avoid the more complex exclusion-based merging, significantly reducing type instantiations.

The changes are identical to those in src/helpers/util.ts, maintaining consistency across the codebase.


138-146: Well-implemented optimization for extendShape type utility

This optimization mirrors the one applied to MergeShapes, creating a fast path for object type merging when keys don't overlap. The implementation is correct and preserves the original behavior while improving performance.

The consistent approach between this file and src/helpers/util.ts ensures unified behavior across different parts of the codebase.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for 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.

Sorry, something went wrong.

Copy link

netlify bot commented Apr 14, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 6a4fdfc
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/67fe214f7ec72c0008a3f048
😎 Deploy Preview https://deploy-preview-4150--guileless-rolypoly-866f8a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@samchungy
Copy link
Contributor

It has been proposed here and, in fact, it cuts AnswerOverflow/apps/dashboard's instantiations from 13672403 to 3538464 (74% reduction) and check time from 6.5s to 4s (38% reduction).

Summary by CodeRabbit

  • Documentation

    • Added "fullproduct.dev" to the "Powered by Zod" section in the README.
  • Refactor

    • Improved type-level merging logic for utility types, optimizing for cases where object keys do not overlap. No impact on runtime behavior.

btw @Andarist, I think this may have already been optimised in Zod 4:
https://v4.zod.dev/v4
#4074

Co-authored-by: Anders Hejlsberg <andersh@microsoft.com>
@Andarist
Copy link
Contributor Author

Given how popular v3 is, I think it still would be good to backport this but, of course, it's up to @colinhacks

@colinhacks
Copy link
Owner

Just when I thought I'd tried every conceivable implementation of ExtendShape Anders drops this fast-path approach. Glorious.

@colinhacks colinhacks merged commit 3e602d4 into colinhacks:main Apr 16, 2025
9 of 10 checks passed
@colinhacks
Copy link
Owner

colinhacks commented Apr 16, 2025

Benchmarks. This builds the somewhat adversarial script in this gist — a chain of .omit() and .extend() calls. I chained as many calls as possible before TS threw an Excessively Deep error, so basically this benchmark is designed to be as impressive as possible 🤷‍♂️ And it is :)

Metric Zod 3.24.2 (Pre-change) Zod 3.24.3 (Post-change) Factor
Total Time 3.15s 0.50s 6.3× faster
Check Time 2.15s 0.15s 14.3× faster
Emit Time 0.69s 0.03s 23.0× faster
Transform Time 0.68s 0.02s 34.0× faster
Instantiations 15,415,384 165,263 98.9% reduction

Zod 3.24.2 (pre-change)

$ pnpm run build:bench

> @zod/tsc-perftest@1.0.0 build:bench /Users/colinmcd94/Documents/projects/zod/packages/tsc
> tsc -p tsconfig.bench.json

Files:                          162
Lines of Library:             39498
Lines of Definitions:         54853
Lines of TypeScript:            107
Lines of JavaScript:              0
Lines of JSON:                    0
Lines of Other:                   0
Identifiers:                  87917
Symbols:                      82218
Types:                         9900
Instantiations:            15415384
Memory used:                119682K
Assignability cache size:      2548
Identity cache size:              6
Subtype cache size:               0
Strict subtype cache size:        0
I/O Read time:                0.01s
Parse time:                   0.16s
ResolveModule time:           0.02s
ResolveTypeReference time:    0.00s
ResolveLibrary time:          0.01s
Program time:                 0.23s
Bind time:                    0.08s
Check time:                   2.15s
transformTime time:           0.68s
commentTime time:             0.00s
I/O Write time:               0.00s
printTime time:               0.69s
Emit time:                    0.69s
Total time:                   3.15s

Zod 3.24.3 (post-change)

$ pnpm run build:bench
> @zod/tsc-perftest@1.0.0 build:bench /Users/colinmcd94/Documents/projects/zod/packages/tsc
> tsc -p tsconfig.bench.json

Files:                         163
Lines of Library:            39498
Lines of Definitions:        54891
Lines of TypeScript:           107
Lines of JavaScript:             0
Lines of JSON:                   0
Lines of Other:                  0
Identifiers:                 87903
Symbols:                     83156
Types:                       10054
Instantiations:             165263
Memory used:               122090K
Assignability cache size:     2673
Identity cache size:             6
Subtype cache size:              0
Strict subtype cache size:       0
I/O Read time:               0.02s
Parse time:                  0.16s
ResolveModule time:          0.02s
ResolveTypeReference time:   0.00s
ResolveLibrary time:         0.01s
Program time:                0.24s
Bind time:                   0.08s
Check time:                  0.15s
transformTime time:          0.02s
commentTime time:            0.00s
I/O Write time:              0.00s
printTime time:              0.03s
Emit time:                   0.03s
Total time:                  0.50s

@jakebailey
Copy link

How did emit time end up shrinking?

@Andarist
Copy link
Contributor Author

@jakebailey serializeTypeForDeclaration can lead to instantiateType calls - and I've verified that this particular emit involves many of those. So given the instantiations were reduced by a large margin - the emit time could also easily go down here.

@Andarist
Copy link
Contributor Author

This builds the somewhat adversarial script in this gist — a chain of .omit() and .extend() calls

I thought this would still perform poorly but it doesnt 🤔

@Andarist Andarist deleted the perf/extendShape branch April 17, 2025 12:46
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.

None yet

4 participants