为什么循环变量的地址在使用时会发生变化?

时间:2016-09-28 11:46:07

标签: r for-loop memory pryr

计划1:

sessionInfo()
R version 3.2.5 (2016-04-14)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 8 (jessie)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=sv_SE.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=sv_SE.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=sv_SE.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] gmailr_0.7.1

loaded via a namespace (and not attached):
[1] httr_1.2.1      magrittr_1.5    R6_2.1.3        base64enc_0.1-3
[5] curl_1.2        Rcpp_0.12.7     jsonlite_1.1    httpuv_1.3.3   
[9] openssl_0.9.4  

输出例如:

 library(pryr)

 for (x in 1:3) {
     print(c(address(x), refs(x)))
 }

计划2:

[1] "0x7a6a6c8" "1"        
[1] "0x7a6a6c8" "1"        
[1] "0x7a6a6c8" "1"

输出例如:

library(pryr)

for (x in 1:3) {
  print(c(address(x), refs(x)))
  print(x)
}

显然,x的价值在计划2中正在发生变化,但为什么地址也会发生变化?当循环运行大约500,000,000次而循环期间没有调用gc时,这会导致内存泄漏吗?

1 个答案:

答案 0 :(得分:1)

在循环的末尾打印(x)将其标记为多引用,如@alexis_laz所述。由于R是一种动态语言,因此很容易发生。为了测试这种效果,我们可以打印refs(x),print(x),refs(x)的输出:

for (x in 1:3) {
  print(refs(x))
  print(x)
  print(refs(x)); cat("\n")
}

输出:

[1] 1
[1] 1
[1] 2

[1] 1
[1] 2
[1] 2

[1] 1
[1] 3
[1] 2