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 cld
## DC() 1547.0 1627.1 2106.3 1682.0 1831.7 22902 100 b
## RC$new() 277.1 292.5 350.0 320.4 363.4 1793 100 a
## R6$new() 54.9 63.9 76.5 71.8 82.5 287 100 a
## RL() 22.3 28.6 35.2 33.7 39.7 101 100 a
## RList() 2.8 3.9 5.7 5.2 6.2 20 100 a
benchmark2 <- microbenchmark(
DCChild(),
RCChild$new(),
R6Child$new(),
RLChild()
)
print(benchmark2, digits = 2)
## Unit: microseconds
## expr min lq mean median uq max neval cld
## DCChild() 3173 3248 3910 3326 3745 30085 100 b
## RCChild$new() 281 305 356 342 377 1410 100 a
## R6Child$new() 220 242 274 266 294 444 100 a
## RLChild() 92 110 123 120 135 229 100 a