我正在 R studio 中运行代码。当我的脚本完成运行时,我在结果底部收到橙色消息
There were 50 or more warnings (use warnings() to see the first 50)
(实际上,我怀疑警告的数量至少有数万)。这些警告是否会减慢我的代码速度,因为它们是 I/O 操作,因此成本高昂?我没有看到任何错误消息,但我不确定 R studio 处理它们的方式,它们是否仍然是 I/O 操作,或者它处理它们的任何方式是否会处理速度减慢问题,我通常会期望这样的导致大量I/O操作。
一般来说,答案是肯定的,生成大量警告的代码会对性能产生一些负面影响,尽管这种影响是否有意义会有所不同。举例说明:
library(bench)
v <- -1000:1000
res <- mark(no_warnings = sapply(abs(v), log),
avoid_warnings = sapply(v, \(x) if (x < 0) NaN else log(x)),
warnings = sapply(v, log), check = FALSE)
There were 50 or more warnings (use warnings() to see the first 50)
结果:
# A tibble: 3 × 13
expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time
<bch:expr> <bch:tm> <bch:t> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm>
1 no_warnings 833.6µs 1.06ms 832. 78.9KB 4.23 393 2 472ms
2 avoid_warnings 1.4ms 2.13ms 418. 73.2KB 6.46 194 3 464ms
3 warnings 53.9ms 56.37ms 17.8 64KB 5.08 7 2 394ms
# … with 4 more variables: result <list>, memory <list>, time <list>, gc <list>
plot(res, type = "boxplot")
根据我的理解,他们会稍微放慢速度,尽管最多可能会稍微超过边际。但是,如果您不需要使用警告中的信息,我建议避免警告,使用类似suppressWarnings()
它们不应该对性能产生任何有意义的影响,除非有数百万个,这是真的,但是:令我惊讶的是,我发现在某些条件下,由
lifecycle::deprecate_warn
生成的警告会使代码变慢很多。即使有一两个。
当我从 RStudio 启动 ShinyApp 时,这种情况一直发生在我身上,并且它似乎特定于在 RStudio 旁边的选项卡中打开应用程序时的情况。
顺便问一下,有人有同样的情况吗?有什么想法为什么会发生吗?