[Rcpp-devel] Call by reference

Nathan Kurz nate at verse.com
Wed Jul 29 22:05:21 CEST 2015


On Wed, Jul 29, 2015 at 10:37 AM, Dirk Eddelbuettel <edd at debian.org> wrote:
> You misunderstand.  We communicate by SEXP.  Where the P stands for pointer.
> IE even with
>
>   R> M <- as.data.frame(matrix(rnorm(1e6, 1e3)))
>   R> object.size(M)
>   8000672 bytes
>   R>
>
> we'd still only pass the same 56 bytes a SEXP takes. See eg
> https://cran.r-project.org/doc/manuals/R-ints.html#SEXPs and play with memory
> profiling in R.

I tried memory profiling both of your versions with a long vector, and
found that the recommended Rcpp approach made an additional 8GB copy.
Is there a way to avoid this extra copy without resorting to in place
modification?

--nate

nate at ubuntu:~/R/byreference$ less abs.R
  library(Rcpp)

  cppFunction("NumericVector absCopy(NumericVector & x) { return abs(x); }")
  cppFunction("void absInPlace(NumericVector & x) { x = abs(x); }")

  xOrig = rnorm(1000*1000*1000)
  xRef = xOrig       # shallow copy shares memory
  xCopy = xOrig * 1  # deep copy is independent

  Rprofmem("absInPlace.txt")
  absInPlace(xOrig)
  Rprofmem(NULL)

  identical(xOrig, xRef)
  identical(xOrig, xCopy)

  Rprofmem("absCopy.txt")
  xCopy = absCopy(xCopy)
  Rprofmem(NULL)

  identical(xOrig, xRef)
  identical(xOrig, xCopy)

nate at ubuntu:~/R/byreference$ Rscript abs.R
  [1] TRUE
  [1] FALSE
  [1] TRUE
  [1] TRUE

nate at ubuntu:~/R/byreference$ cat absInPlace.txt
  2544 :"<Anonymous>" "absInPlace"

nate at ubuntu:~/R/byreference$ cat absCopy.txt
  8000000040 :"<Anonymous>" "absCopy"
  2544 :"<Anonymous>" "absCopy"


More information about the Rcpp-devel mailing list