[R-pkg-devel] setClassUnion and S4 Dispatch Performance

Dario Strbenac d@tr7320 @end|ng |rom un|@@ydney@edu@@u
Fri Dec 3 10:00:06 CET 2021


Good day,

I wonder why the runnable example below takes a long time to finish.

library(SummarizedExperiment) # Or BiocManager::install("SummarizedExperiment") to install it beforehand.

setClassUnion("characterOrMissing", c("character", "missing"))
setClassUnion("integerOrMissing", c("integer", "missing"))
setClass("ParamsSet", representation(A = "characterOrMissing", B = "integer"))
setGeneric("ParamsSet", function(A, B, C, D, E, F, G, H) standardGeneric("ParamsSet"))

setMethod("ParamsSet", c("missing", "missing", "missing", "missing", "missing", "missing", "missing", "missing"),
function() # Empty constructor
{
  new("ParamsSet", A = 'M', B = 300L)
})

setMethod("ParamsSet", c("characterOrMissing", "integerOrMissing", "integerOrMissing", "integerOrMissing",
                         "characterOrMissing", "integerOrMissing", "integerOrMissing", "integerOrMissing"),
function(A = c('L', 'M', 'N'), B = 500, C = 100, D, E, F, G, H)
{
  if(missing(A)) A <- 'L' # Mimick match.arg.
  if(missing(B)) B <- 500L # Hack to implement parameter defaults not specified by generic.
  if(missing(C)) C <- 100L
  new("ParamsSet", A = A, B = B)
})

system.time(ParamsSet(B = 999L)) # Slow or fast, depending on if SummarizedExperiment loaded.

The CPU and RAM usage increase sharply when the above line is run, dependent on SummarizedExperiment in the background. The delay doesn't happen when run a second time, presumably due to caching.

--------------------------------------
Dario Strbenac
University of Sydney
Camperdown NSW 2050
Australia


More information about the R-package-devel mailing list