好吧,又到了救援的时机。似乎switch 通常比if 语句快。
因此,使用switch 语句的代码更短/更整洁的事实倾向于switch:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
更新 考虑到 Joshua 的评论,我尝试了其他方法来进行基准测试。微基准似乎是最好的。 ...它显示了类似的时间:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
最终更新这里展示了switch 的多功能性:
switch(type, case1=1, case2=, case3=2.5, 99)
这会将case2 和case3 映射到2.5,并且(未命名的)默认值映射到99。欲了解更多信息,请尝试?switch