Performance benchmarks

2017-05-06

These performance tests are adapted from the R6 performance documentation. I was curious how the implementations in this package would compare to R6 since one of the main design goals of R6 was to solve some performance issues with the reference classes from the methods package.

Definitions

library("R6")
library("aoos")
library("rbenchmark")

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", {})

Results

benchmark(
  DC(),
  RC$new(),
  R6$new(),
  RL(),
  RList()
)
##       test replications elapsed relative user.self sys.self user.child
## 1     DC()          100   0.178      178     0.180        0          0
## 3 R6$new()          100   0.007        7     0.004        0          0
## 2 RC$new()          100   0.031       31     0.032        0          0
## 4     RL()          100   0.003        3     0.004        0          0
## 5  RList()          100   0.001        1     0.000        0          0
##   sys.child
## 1         0
## 3         0
## 2         0
## 4         0
## 5         0
benchmark(
  DCChild(),
  RCChild$new(),
  R6Child$new(),
  RLChild()
)
##            test replications elapsed relative user.self sys.self
## 1     DCChild()          100   0.378   34.364     0.380        0
## 3 R6Child$new()          100   0.024    2.182     0.024        0
## 2 RCChild$new()          100   0.032    2.909     0.032        0
## 4     RLChild()          100   0.011    1.000     0.008        0
##   user.child sys.child
## 1          0         0
## 3          0         0
## 2          0         0
## 4          0         0