All this is taken from the R6 performance documentation.
library("R6")
library("aoos")
library("microbenchmark")
R6 <- R6Class("R6",
public = list(
x = NULL,
initialize = function(x = 1) self$x <- x,
getx = function() self$x,
inc = function(n = 1) self$x <- x + n
)
)
RC <- setRefClass("RC",
fields = list(x = "numeric"),
methods = list(
initialize = function(x = 1) .self$x <- x,
getx = function() x,
inc = function(n = 1) x <<- x + n
)
)
RList <- function(x = 1) {
self <- environment()
getx <- function() self$x
inc <- function(n = 1) self$x <- self$x + n
out <- list(x = x, getx = getx, inc = inc)
class(out) <- "RList"
out
}
RL <- function(x = 1) {
getx <- function() .self$x
inc <- function(n = 1) .self$x <- .self$x + n
retList("RL", c("x", "getx", "inc"))
}
DC <- defineClass("DC", {
getx <- function() .self$x
inc <- function(n = 1) .self$x <- .self$x + n
init <- function(x = 1) .self$x <- x
})
# And some more definitions for inheritance
R6Child <- R6Class("R6Child", inherit = R6)
RCChild <- setRefClass("RCChild", contains = "RC")
RLChild <- function(...) {
retList("RLChild", super = RL(...))
}
DCChild <- defineClass("DCChild", contains = "DC", {})
benchmark1 <- microbenchmark(
DC(),
RC$new(),
R6$new(),
RL(),
RList()
)
print(benchmark1, digits = 2)
## Unit: microseconds
## expr min lq mean median uq max neval
## DC() 1624.2 1696.7 1947.5 1757.7 1982.3 5252 100
## RC$new() 282.6 304.5 564.1 326.6 373.1 22125 100
## R6$new() 56.4 67.2 79.1 74.5 86.6 154 100
## RL() 22.5 29.5 34.9 32.6 37.5 90 100
## RList() 2.9 4.5 6.1 5.8 7.1 15 100
benchmark2 <- microbenchmark(
DCChild(),
RCChild$new(),
R6Child$new(),
RLChild()
)
print(benchmark2, digits = 2)
## Unit: microseconds
## expr min lq mean median uq max neval
## DCChild() 3347 3517 4857 3590 3778 97596 100
## RCChild$new() 285 305 360 343 388 1295 100
## R6Child$new() 223 244 279 279 303 388 100
## RLChild() 94 108 127 128 138 223 100