Skip to content

using get(x, envir = self) instead of x$self #79

@m-muecke

Description

@m-muecke

I saw that you're are mainly using get(x, envir = self) and get(.x, envir = private) instead of self$x and private$.xrespectively.
As well as with assign(), is that you personal prefence or does it have other reasons, I couldn't find any performance improvements:

Test <- R6::R6Class(
  "Test",
  public = list(
    x = NULL,
    initialize = function(x) {
      self$x <- x
    },
    get1 = function() {
      self$x
    },
    get2 = function() {
      get("x", envir = self)
    },
    get3 = function() {
      private$.y
    },
    get4 = function() {
      get(".y", envir = private)
    }
  ),
  private = list(
    .y = 1:100
  )
)
test <- Test$new(1:100)
bench::mark(test$get1(), test$get2())
#> # A tibble: 2 × 6
#>   expression       min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>  <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 test$get1()    697ns    779ns  1004237.        0B        0
#> 2 test$get2()    779ns    861ns   955973.        0B        0
bench::mark(test$get3(), test$get4())
#> # A tibble: 2 × 6
#>   expression       min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>  <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 test$get3()    369ns    451ns  1898262.        0B     190.
#> 2 test$get4()    738ns    820ns  1100959.        0B       0

Created on 2025-04-09 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions