Search code examples
rr6

R6 store methods by reference instead of copy


I'm creating multiple R6 objects of the same class, my cl class contains some heavy methods.
As my understanding - code below - it seems that each of object has it's own copy of all methods.
How can I have single copy of methods for all my cl objects? S3 stores only single copy of a method, isn't it?
I want to scale it for thousands of cl objects so would prefer to omit overhead.

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"

Solution

  • You shouldn't worry about this.

    Closures are very fast in R. Under the hood it probably has some optimization ticks to recognizes duplicate function definitions and store them in a single place.