我有一个双循环,如下所示 的问题是R(2.15.2)使用越来越多的内存,我不明白为什么.
虽然我知道这必须在内循环中发生,因为rbind()我在那里做,我不明白为什么R在外循环的新循环开始时实际上重复使用对象('xmlCatcher')时继续抓取内存:
# !!!BEWARE this example creates a lot of files (n=1000)!!!!
require(XML)
chunk <- function(x, chunksize){
# source: http://stackoverflow.com/a/3321659/1144966
x2 <- seq_along(x)
split(x, ceiling(x2/chunksize))
}
chunky <- chunk(paste("test",1:1000,".xml",sep=""),100)
for(i in 1:1000){
writeLines(c(paste('<?xml version="1.0"?>\n <note>\n <to>Tove</to>\n <nr>',i,'</nr>\n <from>Jani</from>\n <heading>Reminder</heading>\n ',sep=""), paste(rep('<body>Do not forget me this weekend!</body>\n',sample(1:10, 1)),sep="" ) , ' </note>')
,paste("test",i,".xml",sep=""))
}
for(k in 1:length(chunky)){
gc()
print(chunky[[k]])
xmlCatcher <- NULL
for(i in 1:length(chunky[[k]])){
filename <- chunky[[k]][i]
xml <- xmlTreeParse(filename)
xml <- xmlRoot(xml)
result <- sapply(getNodeSet(xml,"//body"), xmlValue)
id <- sapply(getNodeSet(xml,"//nr"), xmlValue)
dummy <- cbind(id,result)
xmlCatcher <- rbind(xmlCatcher,dummy)
}
save(xmlCatcher,file=paste("xmlCatcher",k,".RData"))
}
Run Code Online (Sandbox Code Playgroud)
有人知道为什么会出现这种行为吗?请注意,所有对象(如'xmlCatcher')在每个周期都会重复使用,因此我假设在第一个"块"周期后使用的RAM应该保持不变.
这是一个错误还是我错过了什么?
你对重用记忆的理解是很好的.
当您创建新的DummyCatcher时,旧的DummyCatcher不再被引用,然后成为垃圾收集的候选者,这将在某个时刻发生.
你没有重用内存,你正在创建一个新对象并放弃旧对象.
垃圾收集将释放内存.
此外,我建议你看看Rprofmem来描述你的记忆使用情况.