R copies for no apparent reason

Some function R will make R copy the object AFTER calling the function, for example, nrow, while some others will not, for example, sum. For example, the following code:

x = as.double(1:1e8)
system.time(x[1] <- 100)
y = sum(x)
system.time(x[1] <- 200)     ## Fast (takes 0s), after calling sum
foo = function(x) {
    return(sum(x))
}
y = foo(x)
system.time(x[1] <- 300)     ## Slow (takes 0.35s), after calling foo

The call to foo is NOT slow because x is not copied. However, changing x again happens very slowly, as x is copied. I assume that calling foo will leave a link to x, so by changing it, R will make another copy.

Does anyone know why R does this? Even if the function does not change x at all? Thanks.

+6
source share
1 answer

Hadley Advanced R , , , , . (, @joran @lmo), , --.

, #:

:

  • R x .

  • R x , , x, .

, R . , . x, R . , pryr . , () refs() , .

RC- Performance. pryr .

( ), :

, , , . , , ++, Rcpp.

0

Source: https://habr.com/ru/post/1015410/


All Articles