How much harm can nested if's do?
The definition of a()
, b()
, and sw()
below achieve the same effect with different implementations: if else
, nested if
, and switch
a <- function(x) {
if (x == 'A') {
paste('Apple')
} else if (x == 'R') {
paste('Ready')
} else if (x == 'N') {
paste('Novel')
} else if (x == 'G') {
paste('Ginger')
} else {
paste("Bingo")
}
}
b <- function(x) {
ifelse (x == 'A', paste('Apple'),
ifelse(x == 'R', paste('Ready'),
ifelse(x == 'N', paste('Novel'),
ifelse(x == 'G', paste('Ginger'),
paste("Bingo")))))
}
sw <- function(x) {
switch (x,
A = paste('Apple'),
R = paste('Ready'),
N = paste('Novel'),
G = paste('Ginger'),
"Bingo"
)
}
Timing
microbenchmark(a('R'), b('R'), sw('R'), times=1000)
## Unit: microseconds
## expr min lq mean median uq max neval
## a("R") 1.389 1.4475 6.090854 1.4890 1.5430 4513.274 1000
## b("R") 3.995 4.1390 9.553401 4.2165 4.3560 4870.285 1000
## sw("R") 1.169 1.2270 21.333951 1.2670 1.3165 19915.547 1000