Skip to content

Consider constructor hot paths - #724

Merged
hadley merged 8 commits into
mainfrom
constructor-perf
Jul 27, 2026
Merged

hadley merged 8 commits into
mainfrom
constructor-perf

Conversation

@hadley

@hadley hadley commented Jul 10, 2026 •

Copy link
Copy Markdown
Member
  • Catch the computed class name and dispatch vector in new S7_class and S7_dispatch attributes
  • Re-implement class_type() in C since it's called a lot, and means we can ensure that the first and last types get the same performance (old: 600-3000ns, new 200-250ns)

Part of #723

This gives a meaningful performance to construction:

Depth main Current Speedup Reduction
0 61.8 µs 45.6 µs 1.36× 26%
5 457.7 µs 241.4 µs 1.90× 47%
10 1,085.4 µs 446.1 µs 2.43× 59%

Depth 0 is one class directly extending S7_object; depths 5 and 10 add that many parent links.

Also helps with S7_inherits() and super():

S7_inherits() and super() were benchmarked using an instance of the deepest class and the root user class as the target.

Depth Operation main Current Speedup Reduction
0 S7_inherits() 11.726 µs 7.872 µs 1.49× 33%
0 super() 26.855 µs 12.751 µs 2.11× 53%

hadley added 7 commits July 10, 2026 08:16
Move class_type() into C so callers avoid a chain of R-level inherits() calls. Read the class attribute once, walk it once, and compare interned CHARSXP pointers while retaining the previous type-priority order for pathological multi-tagged objects.

Preserve and reuse the returned type strings to avoid allocation. Keep a NULL fast path in class_properties() because S7_object is bootstrapped before the DLL is registered; this keeps devtools::load_all() working in a fresh interactive session.

Median class_type() time drops from 615-3,731 ns depending on the class representation to 205-246 ns. Depth-5 and depth-10 construction benchmark at 213 us and 420 us, respectively.

Tests: R_TESTTHAT_QUICK=true Rscript -e 'devtools::test()' (1,200 passed, 3 expected skips).
@hadley
hadley requested a review from t-kalinowski July 27, 2026 20:03
@hadley

hadley commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

@t-kalinowski this doesn't solve all the performance issues, but it's a meaningful improvement.

@t-kalinowski t-kalinowski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Very nice!

@hadley
hadley merged commit cf91dd6 into main Jul 27, 2026
13 checks passed
@hadley
hadley deleted the constructor-perf branch July 27, 2026 22:57
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.

2 participants