Skip to content

Instantly share code, notes, and snippets.

@wch
Created July 10, 2019 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/0bc31ba8b80df3c00c715a5246cfa814 to your computer and use it in GitHub Desktop.
Save wch/0bc31ba8b80df3c00c715a5246cfa814 to your computer and use it in GitHub Desktop.
Modifying a vector in an object
## Modifying a vector in a parent environment
## This tests whether it's faster to use `self` or not, and whether it's faster to use `<-` vs `<<-`.
foo <- local({
x <- integer()
self <- environment()
# Four different ways of setting a value:
# * With and without using `self`
# * With `<-` or with `<<-`
list(
set_self_single = function(i, value) {
self$x[i] <- value
},
set_self_double = function(i, value) {
self$x[i] <<- value
},
set_noself_single = function(i, value) {
x[i] <- value
},
set_noself_double = function(i, value) {
x[i] <<- value
},
reset = function() {
self$x <- integer()
}
)
})
n <- 10000
system.time({
foo$reset()
for (i in seq_len(n)) foo$set_self_single(i, i)
})
#> user system elapsed
#> 0.189 0.049 0.237
system.time({
foo$reset()
for (i in seq_len(n)) foo$set_self_double(i, i)
})
#> user system elapsed
#> 0.191 0.042 0.234
system.time({
foo$reset()
for (i in seq_len(n)) foo$set_noself_single(i, i)
})
#> user system elapsed
#> 0.073 0.021 0.094
system.time({
foo$reset()
for (i in seq_len(n)) foo$set_noself_double(i, i)
})
#> user system elapsed
#> 0.017 0.000 0.016
profvis::profvis({
foo <- local({
x <- integer()
self <- environment()
# Four different ways of setting a value:
# * With and without using `self`
# * With `<-` or with `<<-`
list(
set_self_single = function(i, value) {
self$x[i] <- value
},
set_self_double = function(i, value) {
self$x[i] <<- value
},
set_noself_single = function(i, value) {
x[i] <- value
},
set_noself_double = function(i, value) {
x[i] <<- value
},
reset = function() {
self$x <- integer()
}
)
})
foo$reset()
for (i in seq_len(n)) foo$set_self_single(i, i)
foo$reset()
for (i in seq_len(n)) foo$set_self_double(i, i)
foo$reset()
for (i in seq_len(n)) foo$set_noself_single(i, i)
foo$reset()
for (i in seq_len(n)) foo$set_noself_double(i, i)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment