3

Using Globals instead of passing large arrays in Matlab

my question is precisely the same as the one above but I want an answer with respect to R. I am right now passing huge matrices between functions. The data in the matrix is not changed in those functions. I just use the matrix. My code is running slow. I would like to know if there is an alternative like using globals or object oriented way. Thanks

Community
  • 1
  • 1
saiteja
  • 488
  • 3
  • 12
  • Although conceptually the arguments are copied into functions, in fact the underlying implementation is smart enough to not copy arguments which are not changed so there is no performance slow down. – G. Grothendieck May 17 '13 at 04:01

2 Answers2

5

R has pass-by-reference (sort of). When you assign an object to another variable or pass to a function, another reference is created. However, if you modify the object through one of the references, that's when an actual copy is made.

f <- function(m) {
  .Internal(inspect(m))
}
g <- function(m) {
  m[1] <- 0
  .Internal(inspect(m))
}

m <- matrix(1,1)
.Internal(inspect(m))
## @452e308 14 REALSXP g0c1 [NAM(2),ATT] (len=1, tl=0) 1
## ATTRIB:
##   @42c8ee8 02 LISTSXP g0c0 [] 
##     TAG: @2faaf98 01 SYMSXP g0c0 [MARK,LCK,gp=0x4000] "dim" (has value)
##     @452e2d8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) 1,1

# f shows that this is the same object (@452e308):
f(m)
## @452e308 14 REALSXP g0c1 [NAM(2),ATT] (len=1, tl=0) 1
## ATTRIB:
##   @42c8ee8 02 LISTSXP g0c0 [] 
##     TAG: @2faaf98 01 SYMSXP g0c0 [MARK,LCK,gp=0x4000] "dim" (has value)
##     @452e2d8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) 1,1

# g shows a newly allocated object (@3941998):
g(m)
## @3941998 14 REALSXP g0c1 [NAM(1),ATT] (len=1, tl=0) 0
## ATTRIB:
##   @3b9fc80 02 LISTSXP g0c0 [] 
##     TAG: @2faaf98 01 SYMSXP g1c0 [MARK,LCK,gp=0x4000] "dim" (has value)
##     @3941ae8 13 INTSXP g0c1 [NAM(2)] (len=2, tl=0) 1,1
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
3

There are no "globals" in R. If you want to use pass-by-reference semantics, you can either use the 'data.table' package which might be useful, or you can use environments or ReferenceClasses. At the moment the question is too nebulous to admit of more detail.

IRTFM
  • 258,963
  • 21
  • 364
  • 487