Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(R6)
- library(methods)
- library(microbenchmark)
- make_class4 <- function() {
- cl <- setClass("num_with_id", slots = c(id = "character"),
- contains = "numeric")
- setGeneric("getId", function(x) stop("Not implemented"))
- setMethod("getId", c("num_with_id"), function(x) x@id)
- cl
- }
- num_with_id4 <- make_class4()
- make_instance4 <- function() {
- num_with_id4(1:3, id = "An Example")
- }
- instance4 <- make_instance4()
- call_method4 <- function() {
- getId(instance4)
- }
- ## -----------------------------
- make_class6 <- function() {
- R6Class(
- "num_with_id6",
- cloneable = FALSE,
- public = list(
- data = NULL,
- id = NULL,
- initialize = function(data, id) {
- self$id <- id
- self$data <- data
- },
- getId = function() self$id
- )
- )
- }
- num_with_id6 <- make_class6()
- make_instance6 <- function() {
- num_with_id6$new(1:3, id = "An Example")
- }
- instance6 <- make_instance6()
- call_method6 <- function() {
- instance6$getId()
- }
- ## ------------------------------
- microbenchmark(make_class4(), make_class6(), times = 1000)
- #> Unit: microseconds
- #> expr min lq mean median uq max neval
- #> make_class4() 3782.930 4036.894 4736.39757 4246.9235 4976.1090 56461.682 1000
- #> make_class6() 57.062 68.655 92.39163 90.3715 102.6475 1969.083 1000
- microbenchmark(make_instance4(), make_instance6(), times = 1000)
- #> Unit: microseconds
- #> expr min lq mean median uq max neval
- #> make_instance4() 163.115 172.9755 186.44686 178.0685 184.335 1304.314 1000
- #> make_instance6() 27.697 32.5685 39.62562 39.4375 43.698 1008.130 1000
- microbenchmark(call_method4(), call_method6(), times = 1000)
- #> Unit: microseconds
- #> expr min lq mean median uq max neval
- #> call_method4() 7.360 7.9530 8.571229 8.2580 8.6625 53.650 1000
- #> call_method6() 2.257 2.4325 2.748578 2.6395 2.8375 19.556 1000
Add Comment
Please, Sign In to add comment