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() 1156.1 1293.2 1507 1407.9 1512.9 4603 100
## RC$new() 207.8 244.1 743 269.4 315.5 45129 100
## R6$new() 36.6 51.6 63 55.3 65.1 173 100
## RL() 12.9 16.5 26 23.2 27.1 106 100
## RList() 1.8 2.6 4 3.8 4.6 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() 2491 2632 3099 2733 2934 7925 100
## RCChild$new() 207 246 305 285 329 1436 100
## R6Child$new() 149 176 208 200 225 573 100
## RLChild() 62 80 102 96 112 334 100