Repository navigation
Open
Description
While chatting at useR in Warsaw, @bnaras mentioned that the performance of the S7 constructor could be improved for performance-sensitive applications such as CVXR. This also matches our experience in r-xla/anvl.
It would be good for us to optimize the generated constructor and/or new_object(). Some big performance gains seem achievable with a little caching. @bnaras was kind enough to share a script (generated with AI assistance) demonstrating this:
## Self-contained reproducible example:
## The `paste` overhead in S7's object constructor, and how CVXR's
## `.fast_new` sidesteps it.
##
## THE PROBLEM
## -----------
## Every `new_object()` call rebuilds the class-dispatch vector via S7's
## internal `class_dispatch()`, which walks the parent chain and calls
## S7_class_name(x) == paste(c(x@package, x@name), collapse = "::")
## once per level. For a class N levels deep that is N `paste()` calls on
## EVERY construction -- yet the resulting vector
## c("pkg::Var", "pkg::Leaf", "pkg::Expr", ..., "S7_object")
## is a CONSTANT of the class. CVXR builds it once and caches it.
##
## Writeup: notes/s7_paste_overhead.md . Canonical `.fast_new`:
## CVXR/rsrc_tree/zzz_R_specific/utility.R (ADR D_PERF.1).
##
## Run: Rscript scripts/s7_paste_overhead.R
stopifnot(requireNamespace("S7", quietly = TRUE),
requireNamespace("bench", quietly = TRUE))
library(S7)
## ---------------------------------------------------------------------------
## 1. A 5-level hierarchy, mimicking CVXR's Expression -> Leaf -> Variable
## ---------------------------------------------------------------------------
Expr <- new_class("Expr", package = "demo",
properties = list(id = class_integer))
Node <- new_class("Node", parent = Expr, package = "demo")
Atom <- new_class("Atom", parent = Node, package = "demo")
Leaf <- new_class("Leaf", parent = Atom, package = "demo")
Var <- new_class("Var", parent = Leaf, package = "demo",
properties = list(nm = class_character),
## a normal S7 constructor: the hot path we are measuring
constructor = function(id, nm) {
new_object(S7_object(), id = id, nm = nm)
})
## ---------------------------------------------------------------------------
## 2. CVXR-style .fast_new: cache the dispatch vector once per class,
## attach attributes directly, skip validation. Public S7 API only.
## ---------------------------------------------------------------------------
.fast_new <- local({
cache <- new.env(hash = TRUE, parent = emptyenv())
build_dispatch <- function(cls) {
out <- character(0L); cur <- cls
while (inherits(cur, "S7_class") && !identical(cur, S7::S7_object)) {
out <- c(out, paste0(cur@package, "::", cur@name)) # paste PAID ONCE
cur <- cur@parent
}
c(out, "S7_object")
}
function(.class, .parent, ...) {
cn <- .class@name
cd <- get0(cn, envir = cache, ifnotfound = NULL)
if (is.null(cd)) { cd <- build_dispatch(.class); assign(cn, cd, cache) }
obj <- .parent
attributes(obj) <- c(list(class = cd, S7_class = .class), list(...))
obj
}
})
Var_fast <- function(id, nm) {
if (FALSE) new_object(S7_object()) # S7 static-check guard
.fast_new(Var, S7_object(), id = id, nm = nm)
}
## ---------------------------------------------------------------------------
## 3. Correctness: the two paths produce identical objects
## ---------------------------------------------------------------------------
a <- Var(1L, "x")
b <- Var_fast(1L, "x")
stopifnot(identical(class(a), class(b)),
identical(a@id, b@id), identical(a@nm, b@nm),
S7_inherits(b, Expr), S7_inherits(b, Leaf))
cat("class vector:", paste(class(a), collapse = " < "), "\n\n")
## ---------------------------------------------------------------------------
## 4. Where the time goes: profile 2e5 normal constructions
## ---------------------------------------------------------------------------
pf <- tempfile(fileext = ".out")
Rprof(pf, interval = 0.002)
for (i in 1:200000L) Var(i, "x")
Rprof(NULL)
cat("---- Rprof: self-time hot spots in the normal constructor ----\n")
print(head(summaryRprof(pf)$by.self, 12))
## ---------------------------------------------------------------------------
## 5. Benchmark: normal vs fast (report GC-free `min` and mem_alloc first)
## ---------------------------------------------------------------------------
cat("\n---- bench::mark (single construction) ----\n")
bm <- bench::mark(
normal = Var(1L, "x"),
fast = Var_fast(1L, "x"),
check = FALSE, min_iterations = 5000
)
print(bm[, c("expression", "min", "median", "mem_alloc", "n_gc")])
cat(sprintf("\nspeedup (median normal / median fast): %.1fx\n",
as.numeric(bm$median[1]) / as.numeric(bm$median[2])))This produces the following output with the current CRAN release of S7:
class vector: demo::Var < demo::Leaf < demo::Atom < demo::Node < demo::Expr < S7_object
---- Rprof: self-time hot spots in the normal constructor ----
# A data.frame: 12 × 4
self.time self.pct total.time total.pct
<dbl> <dbl> <dbl> <dbl>
1 0.856 16.9 1.40 27.8
2 0.558 11.0 0.606 12
3 0.446 8.83 0.978 19.4
4 0.322 6.37 5.01 99.2
5 0.322 6.37 0.678 13.4
6 0.302 5.98 2.52 50.0
7 0.276 5.46 0.276 5.46
8 0.214 4.24 0.214 4.24
9 0.2 3.96 0.458 9.07
10 0.146 2.89 0.306 6.06
11 0.14 2.77 0.76 15.0
12 0.12 2.38 1.10 21.7
---- bench::mark (single construction) ----
# A tibble: 2 × 5
expression min median mem_alloc n_gc
<bch:expr> <bch:tm> <bch:tm> <bch:byt> <dbl>
1 normal 42.44µs 47.52µs 0B 27
2 fast 2.34µs 2.71µs 9.99KB 2
speedup (median normal / median fast): 17.6x
Metadata
Metadata
Assignees
Labels
No labels
Activity
hadley commentedon Jul 27, 2026
Analysis from codex given #724
The issue's literal script still reproduces on S7 0.2.2: normal construction takes 48.1 µs and its unchecked
.fast_new()takes 2.95 µs. The literal script no longer runs on development S7 becausenew_object(S7_object())is now rejected when the immediate parent is a concrete non-root class. I used an abstract hierarchy to preserve the intended single-new_object()shape, and a concrete generated hierarchy to represent current semantics.1. Dispatch caching has already delivered the largest measured improvement
The current work successfully removes repeated dispatch construction from the hot path. For a depth-five class,
class_dispatch()fell from 47.8 µs onmainto 0.86 µs, about 55 times faster.This produces increasingly large constructor gains as hierarchy depth grows:
mainclass_dispatch()no longer appears prominently in the full constructor profile, so further work should focus elsewhere.2. Collapsing generated default-constructor chains is the largest remaining opportunity
A concrete depth-five generated constructor takes 212 µs, while an equivalent validated one-shot construction takes 69 µs. Each generated class currently calls its parent constructor and then calls
new_object()again, repeating general setup, parent checks, and validation bookkeeping at every level.Fusing consecutive S7-generated constructors into one construction step has a measured ceiling of roughly a threefold improvement at depth five. It should retain calls to user-supplied constructors and preserve setter, override, and validator semantics, so this is the highest-reward but highest-risk change.
3. Property validation dominates wide classes
Validation accounts for about 83% of construction time for a class with 50 base-type properties:
For a base-type property,
prop_validate()first callsclass_inherits()to check the underlying type, then calls the base class validator, which checks the same underlying type again. A prototype that skipped this redundant second check reduced the 50-property benchmark from about 400 µs to 269 µs, a 33% reduction. It improved the two-property issue-shaped case by about 8%.After removing that duplication, moving more of
validate_properties()into C would address the remaining per-property R call overhead.4. Empty validator hierarchies are expensive
The issue-shaped hierarchy has no class validators, but walking the hierarchy and repeatedly calling
class_validate()is still costly. Removing only the class-validator walk reduced the depth-five one-shot benchmark from 70.3 µs to 41.4 µs, a 41% reduction. The same experiment reduced a generated depth-five constructor from 215.2 µs to 194.0 µs.An S7-specific fast path could read each class's validator attribute directly, or each class could cache whether its ancestry contains any validators. The general S3, S4, and external-class validation paths would only be needed when the hierarchy actually reaches one of those class types.
5. General
new_object()bookkeeping remains substantialWith validation mocked out, the issue-shaped constructor still takes about 21.5 µs versus approximately 3.1 µs for
.fast_new(). The structural profile is led by:@accessvapply()sys.function()class discoveryCaching the names of properties with setters would eliminate the
vapply()scan for the common no-setter case. Empty...could also bypass setter selection, storage-name conversion, and parent-property reset checks.Generated constructors could eventually call an internal helper that receives the class directly, avoiding
sys.function(), while custom constructors would continue using the public stack-inspecting path.6. Internal
@access has an avoidable compatibility costInternal
class@fieldexpressions currently resolve through S7's R-level compatibility wrapper, which performsinherits(),substitute(), and a property lookup. Temporarily binding internal@to base's primitive on R 4.3 and later reduced:This is an 11–13% improvement for hierarchy-heavy cases, though it did not materially improve the 50-property benchmark. Direct internal attribute access for class metadata may provide a similar cross-version optimization.
7. Parent detection has a smaller fast-path opportunity
has_S7_class()currently checks ordinary class representations before calling the C helper that reads the stored S7 class. Trying the C helper first reduced:has_S7_class()from 1.27 µs to 0.33 µs.This is a small and relatively isolated optimization after the larger validation and constructor-chain work.
Suggested implementation order
@access on R 4.3 and later.has_S7_class()for S7 instances.Don't check base property types twice (#723)
Cut fixed bookkeeping cost in `new_object()` (#723)
Cache each class's hierarchy of validators (#723)
Check for a stored S7 class first in `has_S7_class()` (#723)
Don't check base property types twice (#723)
Don't check base property types twice (#723)
Don't check base property types twice (#723)
Cache each class's hierarchy of validators (#723)
hadley commentedon Jul 30, 2026
I reran
bench/constructor.Rback-to-back against v0.2.2 andmainat 91f4140 on arm64 with R 4.5.3. These are median times; timings are rounded to two significant digits.mainvalidate()at depth 5class_dispatch()at depth 5S7_inherits()@property accessprop()property accessThe hierarchy-focused constructor work has therefore produced substantial gains that grow with depth. The benchmark also flags regressions for wide classes and
S7_inherits()compared with the last release.