R6 通过引用而不是复制来存储方法
R6 store methods by reference instead of copy
我正在创建多个相同 class 的 R6 对象,我的 cl
class 包含一些繁重的方法。
据我了解-下面的代码-似乎每个对象都有自己的所有方法副本。
我怎样才能为我的所有 cl
对象拥有单一的方法副本? S3 只存储方法的单个副本,不是吗?
我想为数千个 cl
对象扩展它,所以我宁愿忽略开销。
library(R6)
cl <- R6Class(
classname = "cl",
public = list(
a = numeric(),
b = numeric(),
initialize = function(x){ self$a <- rnorm(1, x); self$b <- rnorm(1, x) },
heavy_method = function() self$a + self$b,
print = function() self$heavy_method())
)
group_of_cl <- lapply(1:3, cl$new)
lapply(group_of_cl, ls.str)
## [[1]]
## a : num 1.7
## b : num 0.898
## heavy_method : function ()
## initialize : function (x)
## print : function ()
##
## [[2]]
## a : num 2.64
## b : num -0.29
## heavy_method : function ()
## initialize : function (x)
## print : function ()
##
## [[3]]
## a : num 3.66
## b : num 1.72
## heavy_method : function ()
## initialize : function (x)
## print : function ()
library(data.table)
sapply(lapply(group_of_cl, `[[`, "heavy_method"),address)
## [1] "0x31de440" "0x3236420" "0x32430a8"
你不应该担心这个。
闭包在 R 中是 very fast。在引擎盖下它可能有一些优化标记来识别重复的函数定义并将它们存储在一个地方。
我正在创建多个相同 class 的 R6 对象,我的 cl
class 包含一些繁重的方法。
据我了解-下面的代码-似乎每个对象都有自己的所有方法副本。
我怎样才能为我的所有 cl
对象拥有单一的方法副本? S3 只存储方法的单个副本,不是吗?
我想为数千个 cl
对象扩展它,所以我宁愿忽略开销。
library(R6)
cl <- R6Class(
classname = "cl",
public = list(
a = numeric(),
b = numeric(),
initialize = function(x){ self$a <- rnorm(1, x); self$b <- rnorm(1, x) },
heavy_method = function() self$a + self$b,
print = function() self$heavy_method())
)
group_of_cl <- lapply(1:3, cl$new)
lapply(group_of_cl, ls.str)
## [[1]]
## a : num 1.7
## b : num 0.898
## heavy_method : function ()
## initialize : function (x)
## print : function ()
##
## [[2]]
## a : num 2.64
## b : num -0.29
## heavy_method : function ()
## initialize : function (x)
## print : function ()
##
## [[3]]
## a : num 3.66
## b : num 1.72
## heavy_method : function ()
## initialize : function (x)
## print : function ()
library(data.table)
sapply(lapply(group_of_cl, `[[`, "heavy_method"),address)
## [1] "0x31de440" "0x3236420" "0x32430a8"
你不应该担心这个。
闭包在 R 中是 very fast。在引擎盖下它可能有一些优化标记来识别重复的函数定义并将它们存储在一个地方。