2

the following code

require(R6)
Array <- R6Class(
  "Array",
  public=list(
    x=matrix(0,0,0),
    initialize=function(a,b,c){
      self$x <- matrix(a,b,c)
    },
    assign=function(z){
      self$x[1,1] <- z
      invisible(self)
    }
  )
)
x <- Array$new(0,10,10)
tracemem(x$x)
x$assign(1)
y <- matrix(0,10,10)
tracemem(y)
y[1,1] <- 1

yields this output

> [1] "<0x55ae7be40040>"
> tracemem[0x55ae7be40040 -> 0x55ae7b403700]: <Anonymous> 
> > [1] "<0x55ae7b254c90>"
> > 

which implies that when the R6 member array is updated a copy of the array is made, whereas when the plain array is updated, the element is update "in-place" (i.e. no copy is generated).

Any idea how I can achieve this for the R6 object?

user1407220
  • 353
  • 1
  • 12
  • 1
    AFAIR the fact that no copy is made for the direct assignment is an optimisation in the R interpreter VM that relies on heuristics to figure out that the object can be safely modified in-place, and it is *very* conservative in its estimates (and thus performs unnecessary copies as in the case you’ve found). There’s probably nothing from within R that we can do to change that, the change would have to happen in the source code of the R VM itself. – Konrad Rudolph Aug 25 '23 at 13:56
  • 1
    Also, are you testing this in RStudio? Or are you using the R executable directly? Some times using RStudio creates extra copies because it displays information in the Environment Browser. At least that used to be very common. Haven't tested in the latest versions of the IDE – MrFlick Aug 25 '23 at 15:13
  • @MrFlick that is fascinating - I'm finding the same issue in VScode. If I run this as an attached R session (which has a similar environment browser to RStudio) then even `y` is copied on modify. But if I just run it in a terminal (even within VScode) it is not. I had no idea - I'm wondering if this ever makes a practical difference to the code I'm running. A quick check suggests it doesn't seem to affect `data.table`, which I generally use with datasets that take a noticeable amount of time to copy, so I'm hoping not... – SamR Aug 25 '23 at 16:02

0 Answers0