Skip to content

Conversation

@eitsupi
Copy link
Contributor

@eitsupi eitsupi commented Nov 26, 2025

Close #522

Allows us to create a constructor separately from the S7 class definition.
The expected use is to create an empty (invalid) object when the package is loaded, and then the second constructor sets properties on it and creates a valid object.

It is also possible for the first constructor of the S7 class to depend on the second constructor.

The second constructor may completely bypass the validation step, making object creation much faster, which I think is very important in packages like polars where we create objects multiple times.
(It is entirely up to the package developer to ensure that the second constructor creates a valid object without validation.)

library(S7)

new_sums <- function(x) {
  out <- EMPTY_SUMS
  value <- x |> Reduce(f = `+`) |> as.integer()
  prop(out, "value", check = FALSE) <- value
  out
}

Sums <- new_class(
  "Sums",
  properties = list(value = class_integer),
  constructor = function(...) {
    v <- new_sums(list(...))@value
    new_object(
      S7_object(),
      value = v
    )
  }
)

EMPTY_SUMS <- new_empty_object(Sums)

bench::mark(
  sums1 = Sums(1, 2, 3),
  sums2 = new_sums(list(1, 2, 3))
)
#> # A tibble: 2 × 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 sums1       68.81µs     80µs    11654.   39.27KB     19.0
#> 2 sums2        4.92µs   6.29µs   143152.    4.14MB     28.6

Created on 2025-11-26 with reprex v2.1.1

@eitsupi eitsupi marked this pull request as draft November 26, 2025 14:56
@eitsupi eitsupi changed the title Allow create another constructor with new_empty_object() Allow create another constructor (without validation) with new_empty_object() Nov 26, 2025
@eitsupi eitsupi changed the title Allow create another constructor (without validation) with new_empty_object() Allow creating another constructor (without validation) with new_empty_object() Nov 26, 2025
@eitsupi eitsupi marked this pull request as ready for review November 26, 2025 23:06
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.

Multiple constructors? / Separation of S7 classes and constructors

1 participant