Last active
August 29, 2024 20:09
-
-
Save jonocarroll/41f88c747f9b841c757a2909f9e92bcd to your computer and use it in GitHub Desktop.
Understanding R's copy-on-modify semantics wrt the symbol table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Modify a vector in the workspace; x is a user-accessible symbol | |
x <- 42 | |
.Internal(inspect(x)) | |
# @5631a3a19e20 14 REALSXP g0c1 [REF(5)] (len=1, tl=0) 42 | |
x[1] <- 43 # modification causes a copy (address changes) | |
.Internal(inspect(x)) | |
# @5631a36c1cb8 14 REALSXP g0c1 [REF(4)] (len=1, tl=0) 43 | |
## Modify a vector inside a function; user cannot access y | |
f <- function() { | |
y <- 42 # this value is not accessible outside of the function | |
.Internal(inspect(y)) | |
y[1] <- 43 # modification causes a copy (address changes) | |
.Internal(inspect(y)) | |
rm(y) | |
invisible() | |
} | |
f() | |
# @5631a192c090 14 REALSXP g0c1 [REF(2)] (len=1, tl=0) 42 | |
# @5631a1863f10 14 REALSXP g0c1 [REF(1)] (len=1, tl=0) 43 | |
## Compile? Now they're the same address | |
g <- compiler::cmpfun(f) | |
g() | |
# @56319daa6728 14 REALSXP g0c1 [REF(1)] (len=1, tl=0) 42 | |
# @56319daa6728 14 REALSXP g0c1 [REF(1)] (len=1, tl=0) 43 | |
## The bytecode appears to be exactly the same between f and g | |
# rbytecode::dis(f) | |
# rbytecode::dis(g) | |
# diffobj::diffObj(rbytecode::dis(f), rbytecode::dis(g)) | |
identical(rbytecode::dis(f), rbytecode::dis(g)) | |
# TRUE |
Author
jonocarroll
commented
Nov 6, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment