knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(enumr, quietly = TRUE) library(dplyr) library(ggplot2)
Enum definition is reasonably fast, so will likely not be a bottleneck for the large majority of users. However, if speed is of concern, there are some things to keep in mind:
Here is a microbenchmark, comparing the various forms of enum.
options(scipen = 5) # Create some symbols in the environment # for benchmarking a <- 1 b <- 2 c <- 3 d <- 4 e <- 5 res <- microbenchmark::microbenchmark( inferred <- enum(a, b, c, d, e), explicit_num_symbols <- enum( a = 1, b = .$a + 1, c = .$b + 1, d = .$c + 1, e = .$d + 1 ), explicit_numeric <- enum(a = 1, b = 2, c = 3, d = 4, e = 5), generic_symbols <- enum(a = a, b = b, c = c, d = d, e = e), generic <- enum(a = "1", b = "2", c = "3", d = "4", e = "5"), times = 5000 ) res %>% ggplot2::autoplot() + ggplot2::scale_x_discrete( labels = c( "inferred\nenum(a, b, c, d, e)", "explicit_num_symbols\nenum(a = 1, b = .$a + 1...)", "explicit_numeric\nenum(a = 1, b = 2, c = 3, d = 4, e = 5)", "generic_symbols\nenum(a = a, b = b, c = c, d = d, e = e)", "generic\nenum(a = '1', b = '2', c = '3', d = '4', e = '5')" ) )
This is slower than the standard base::list()
method, largely due to the extra checks that enums do in the background. This isn't to say that enums are slow, but rather that they are not as performant as a primitive list.
To speed up performance further, you can also access the enum constructor methods directly: new_generic_enum()
and new_numeric_enum()
. You'll see these are slightly faster than the enum()
function (the speed increase will likely be in the microsecond range). This is because enum()
has to check whether the enum is numeric or generic by evaluating each argument supplied to it.
res2 <- microbenchmark::microbenchmark( num <- enum(x = 1, y = 2, z = 3), num_constructor <- new_numeric_enum(list(x = 1, y = 2, z = 3)), gen <- enum(x = "1", y = "2", z = "3"), gen_constructor <- new_generic_enum(list(x = "1", y = "2", z = "3")), times = 5000 ) res2 %>% ggplot2::autoplot() + ggplot2::scale_x_discrete( labels = c( "num\nenum(x = 1, y = 2, z = 3)", "num_constructor\nnew_numeric_enum(list(x = 1, y = 2, z = 3))", "gen\nenum(x = '1', y = '2', z = '3')", "gen_constructor\nnew_generic_enum(list(x = '1', y = '2', z = '3'))" ) )
However, this forgoes some of the niceties of the enum()
helper function, such as NSE or implicit definition.
# Can only use explicit definitions new_numeric_enum(list(a, b, c)) # Can't use NSE new_numeric_enum(list(a = 1, b = .$a + 1, c = 4))
Technically, you can use substitute()
to still make use of these features, but this can be cumbersome after a while.
new_numeric_enum( list( x = 5, y = substitute(.$x + 5), substitute(z), substitute(a) ) )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.