Skip to content

Constructor performance #723

Open
Open

Description

@t-kalinowski

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

Activity

  1. hadley commented on Jul 27, 2026

    @hadley
    Member

    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 because new_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 on main to 0.86 µs, about 55 times faster.

    This produces increasingly large constructor gains as hierarchy depth grows:

    Generated hierarchy depth main Current Speedup
    1 74.0 µs 52.8 µs 1.40x
    5 396.1 µs 212.1 µs 1.87x
    10 976.1 µs 405.2 µs 2.41x
    20 2,934.9 µs 859.2 µs 3.42x

    class_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:

    Properties Current median
    0 36.4 µs
    2 52.4 µs
    10 110.3 µs
    50 404.9 µs

    For a base-type property, prop_validate() first calls class_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 substantial

    With 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:

    Operation Share of structural profile
    Internal @ access 30%
    Setter detection through vapply() 17%
    sys.function() class discovery 15%
    Parent checking 13%
    Attribute-name deduplication 5%
    Dot collection 5%

    Caching 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 cost

    Internal class@field expressions currently resolve through S7's R-level compatibility wrapper, which performs inherits(), substitute(), and a property lookup. Temporarily binding internal @ to base's primitive on R 4.3 and later reduced:

    • The issue-shaped depth-five case from 70.0 µs to 61.3 µs.
    • The generated depth-five case from 210.1 µs to 187.7 µs.

    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.
    • S7 parent inheritance checking from 2.30 µs to 1.31 µs.
    • A generated depth-five constructor by about 4%.

    This is a small and relatively isolated optimization after the larger validation and constructor-chain work.

    Suggested implementation order

    1. Remove redundant base-property validation.
    2. Fast-path S7 validator traversal, especially hierarchies with no validators.
    3. Cache setter-property names and add an empty-property fast path.
    4. Optimize internal @ access on R 4.3 and later.
    5. Reorder has_S7_class() for S7 instances.
    6. Investigate collapsing chains of generated default constructors after the lower-risk changes establish a new baseline.
  2. hadley commented on Jul 30, 2026

    @hadley
    Member

    I reran bench/constructor.R back-to-back against v0.2.2 and main at 91f4140 on arm64 with R 4.5.3. These are median times; timings are rounded to two significant digits.

    Case v0.2.2 main Change
    Depth 1 30 µs 24 µs 1.2x faster
    Depth 5 230 µs 120 µs 2.0x faster
    Depth 10 630 µs 230 µs 2.7x faster
    One-shot depth 5 98 µs 32 µs 3.1x faster
    Width 0 29 µs 23 µs 1.3x faster
    Width 2 42 µs 40 µs 1.1x faster
    Width 10 88 µs 99 µs 1.1x slower
    Width 50 320 µs 400 µs 1.3x slower
    Setter 44 µs 42 µs 1.0x faster
    Custom constructor 36 µs 33 µs 1.1x faster
    validate() at depth 5 32 µs 31 µs 1.0x faster
    class_dispatch() at depth 5 39 µs 0.80 µs 49x faster
    S7_inherits() 0.70 µs 7.6 µs 11x slower
    @ property access 0.90 µs 0.60 µs 1.5x faster
    prop() property access 0.30 µs 0.20 µs 1.5x faster

    The 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions