0

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"
jangorecki
  • 16,384
  • 4
  • 79
  • 160

1 Answers1

1

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.

Jeroen Ooms
  • 31,998
  • 35
  • 134
  • 207
  • Creating is very fast, but what about memory? At worst case I would have around 5-10 methods for 200-1000 lines of code each. Should I worry if I create 10k-1m objects of that class and store them in data.frame column? – jangorecki Apr 15 '15 at 23:34
  • 1
    This is all very cachable, let other people worry about that, just focus on your code. – Jeroen Ooms Apr 15 '15 at 23:39
  • 1
    Thanks, accepting. Possibility to store methods by reference gives ability to update a method for all already existing objects of that class. It looks like outsourcing the method to external environment will be enough: `heavy_method = sum` and I get the same memory address. – jangorecki Apr 15 '15 at 23:44