Guest User

Untitled

a guest
Mar 22nd, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. library(R6)
  2. library(methods)
  3. library(microbenchmark)
  4.  
  5. make_class4 <- function() {
  6. cl <- setClass("num_with_id", slots = c(id = "character"),
  7. contains = "numeric")
  8. setGeneric("getId", function(x) stop("Not implemented"))
  9. setMethod("getId", c("num_with_id"), function(x) x@id)
  10. cl
  11. }
  12.  
  13. num_with_id4 <- make_class4()
  14.  
  15. make_instance4 <- function() {
  16. num_with_id4(1:3, id = "An Example")
  17. }
  18.  
  19. instance4 <- make_instance4()
  20.  
  21. call_method4 <- function() {
  22. getId(instance4)
  23. }
  24.  
  25. ## -----------------------------
  26.  
  27. make_class6 <- function() {
  28. R6Class(
  29. "num_with_id6",
  30. cloneable = FALSE,
  31. public = list(
  32. data = NULL,
  33. id = NULL,
  34. initialize = function(data, id) {
  35. self$id <- id
  36. self$data <- data
  37. },
  38. getId = function() self$id
  39. )
  40. )
  41. }
  42.  
  43. num_with_id6 <- make_class6()
  44.  
  45. make_instance6 <- function() {
  46. num_with_id6$new(1:3, id = "An Example")
  47. }
  48.  
  49. instance6 <- make_instance6()
  50.  
  51. call_method6 <- function() {
  52. instance6$getId()
  53. }
  54.  
  55. ## ------------------------------
  56.  
  57. microbenchmark(make_class4(), make_class6(), times = 1000)
  58.  
  59. #> Unit: microseconds
  60. #> expr min lq mean median uq max neval
  61. #> make_class4() 3782.930 4036.894 4736.39757 4246.9235 4976.1090 56461.682 1000
  62. #> make_class6() 57.062 68.655 92.39163 90.3715 102.6475 1969.083 1000
  63.  
  64. microbenchmark(make_instance4(), make_instance6(), times = 1000)
  65.  
  66. #> Unit: microseconds
  67. #> expr min lq mean median uq max neval
  68. #> make_instance4() 163.115 172.9755 186.44686 178.0685 184.335 1304.314 1000
  69. #> make_instance6() 27.697 32.5685 39.62562 39.4375 43.698 1008.130 1000
  70.  
  71. microbenchmark(call_method4(), call_method6(), times = 1000)
  72.  
  73. #> Unit: microseconds
  74. #> expr min lq mean median uq max neval
  75. #> call_method4() 7.360 7.9530 8.571229 8.2580 8.6625 53.650 1000
  76. #> call_method6() 2.257 2.4325 2.748578 2.6395 2.8375 19.556 1000
Add Comment
Please, Sign In to add comment