Repository navigation
Closed
Description
Unfortunately sys.function() makes a deep copy of the class, meaning that we make a lot of unnecessary duplicates with both increases memory consumption and makes various identical() comparisons slower.
library(S7)
library(lobstr)
compare_addresses <- function(...) {
expressions <- as.list(substitute(list(...)))[-1]
x <- list(...)
addresses <- obj_addrs(x)
data.frame(
expression = vapply(expressions, deparse1, character(1)),
address = addresses,
same_as_first = addresses == addresses[[1]],
row.names = NULL
)
}
# Constructing instances ---------------------------------------------------
Foo := new_class(properties = list(x = class_double), package = NULL)
x <- Foo(x = 1)
y <- Foo(x = 2)
# On main, each instance contains a duplicate of Foo.
compare_addresses(
Foo,
S7_class(x),
S7_class(y)
)
# Serializing a class ------------------------------------------------------
class_path <- tempfile(fileext = ".rds")
saveRDS(Foo, class_path)
Foo_rds <- readRDS(class_path)
x_rds <- Foo_rds(x = 1)
y_rds <- Foo_rds(x = 2)
compare_addresses(
Foo_rds,
S7_class(x_rds),
S7_class(y_rds)
)
# The restored generator has a new address, as expected.
compare_addresses(Foo, Foo_rds)
# Serializing instances ---------------------------------------------------
instances_path <- tempfile(fileext = ".rds")
saveRDS(list(x, y), instances_path)
xy_rds <- readRDS(instances_path)
# Restored instances contain separate copies of the class.
# R's serializer preserves sharing for environments, but not closures.
compare_addresses(
S7_class(xy_rds[[1]]),
S7_class(xy_rds[[2]])
)
# Installing and loading a package ----------------------------------------
pkg <- file.path(tempdir(), "s7address")
dir.create(file.path(pkg, "R"), recursive = TRUE)
writeLines(
c(
"Package: s7address",
"Version: 0.0.0.9000",
"Title: S7 Address Reprex",
"Description: A temporary package used to inspect S7 class addresses.",
"License: MIT",
paste0(
"Authors@R: person(\"A\", \"Person\", email = \"[email protected]\", ",
"role = c(\"aut\", \"cre\"))"
),
"Imports: S7"
),
file.path(pkg, "DESCRIPTION")
)
writeLines(
c(
"export(Foo)",
"importFrom(S7,\":=\")",
"importFrom(S7,class_double)",
"importFrom(S7,new_class)"
),
file.path(pkg, "NAMESPACE")
)
writeLines(
"Foo := new_class(properties = list(x = class_double))",
file.path(pkg, "R", "classes.R")
)
lib <- file.path(tempdir(), "s7address-lib")
dir.create(lib)
install.packages(
pkg,
lib = lib,
repos = NULL,
type = "source",
quiet = TRUE,
INSTALL_opts = c("--no-byte-compile", "--no-test-load")
)
invisible(loadNamespace("s7address", lib.loc = lib))
pkg_Foo <- getExportedValue("s7address", "Foo")
pkg_x <- pkg_Foo(x = 1)
pkg_y <- pkg_Foo(x = 2)
compare_addresses(
pkg_Foo,
S7_class(pkg_x),
S7_class(pkg_y)
)Metadata
Metadata
Assignees
Labels
No labels
Activity
🤖🔧 Support the S7 class reference of S7 > 0.2.1