Referenser vs. kopior

Skalbar databehandling i R

Simon Urbanek

Member of R-Core, Lead Inventive Scientist, AT&T Labs Research

Stora matriser och matriser – likheter

  • Delmängd
  • Tilldela
Skalbar databehandling i R

Stora matriser och matriser – skillnader

  • big.matrix lagras på disk
  • Består mellan R-sessioner
  • Kan delas mellan R-sessioner
Skalbar databehandling i R

R skapar vanligtvis kopior vid tilldelning

Detta skapar en kopia av a och tilldelar den till b.

a <- 42
b <- a
a
42
b
42
a <- 43
a
43
b
42
Skalbar databehandling i R

R skapar vanligtvis kopior vid tilldelning

a <- 42

foo <- function(a){a <- 43 paste("Inside the function a is", a)}
foo(a)
"Inside the function a is 43"
paste("Outside the function a is still", a)
"Outside the function a is still 42"
Skalbar databehandling i R

Inte alla R-objekt kopieras

Den här funktionen ändrar faktiskt värdet på a i den globala miljön

foo <- function(a) {a$val <- 43 
                    paste("Inside the function a is", a$val)}
a <- environment()
a$val <- 42
foo(a)
"Inside the function a is 43"
paste("Outside the function a$val is", a$val)
"Outside the function a$val is 43"
Skalbar databehandling i R

`deepcopy()`

# x is a big matrix
x <- big.matrix(...)

# x_no_copy and x refer to the same object
x_no_copy <- x

# x_copy and x refer to different objects
x_copy <- deepcopy(x)

Skalbar databehandling i R

Referensbeteende

R skapar inte kopior implicit

  • Minimerar minnesanvändning
  • Minskar körtid
Skalbar databehandling i R

Inte alla R-objekt kopieras

library(bigmemory)

x <- big.matrix(nrow = 1, ncol = 3, type = "double", 
                init = 0, 
                backingfile = "hello-bigmemory.bin", 
                descriptorfile = "hello-bigmemory.desc")
Skalbar databehandling i R

Inte alla R-objekt kopieras

x_no_copy <- x
x[,]
0 0 0
x_no_copy[,]
0 0 0
x[,] <- 1
x[,]
1 1 1
x_no_copy[,]
1 1 1
Skalbar databehandling i R

Inte alla R-objekt kopieras

x_copy <- deepcopy(x)
x[,]
1 1 1
x_copy[,]
1 1 1
x[,] <- 2
x[,]
2 2 2
x_copy[,]
1 1 1
Skalbar databehandling i R

Nu kör vi en övning!

Skalbar databehandling i R

Preparing Video For Download...