更新问题(对管理员:如果它不值得单独的答案 - 请将其与原始答案合并)。mgsub
与简单的for循环相比,运行速度如此之快的原因是默认情况下在mgsub
参数fixed = TRUE
中,而默认情况下!我刚刚发现它。我想再次澄清一下,这不适合我,因为我不想替换in ,而只想替换整个单词。即我被迫将s 粘贴到模式中。这是我的代码中的三个片段(我测试只是为了查看时差,不打算使用它)。gsub
FALSE
fixed=TRUE
caps
capsule
caps
\\b
fixed=TRUE
gsub
#This is with mgsub. Now with fixed = FALSE!!
i = mgsub(paste("\\b",orig,"\\b",sep=""),change,i,fixed=FALSE)
#This is with a for loop. fixed=TRUE in one of lines is for test purposes only. Do not use
for(k in seq_along(orig)) {
i = gsub(paste("\\b",orig[k],"\\b",sep=""),change[k],i)
#i = gsub(orig[k],change[k],i,fixed=TRUE)
}
以下是在不同数量的输入数据上所有三种情况的时间和内存使用情况:
N | mgsub, fixed=F | gsub, fixed=F | gsub, fixed=T
--------------------------------------------------------------
100k | 41sec, M > 2.3GB | 37sec, M > 0.9GB | 9sec, M > 0.8GB
200k | 99sec, M > 4GB | 74sec, M > 1.1GB | 18sec, M > 1.3GB
300k | 132sec, M > 5.6GB| 112sec, M > 2.6GB| 28sec, M > 1.6GB
+ disk involved
因此,我得出结论,对于我的应用程序 when fixed
must be FALSE
,使用mgsub
. 其实for
loop更快,不会造成内存溢出!
感谢所有相关人员。我希望我可以给评论者积分,但我不知道如何在“评论”中做到这一点