Skip to content

Instantly share code, notes, and snippets.

@sgibb
Created July 17, 2019 14:45
Show Gist options
  • Save sgibb/6c95ea17296b68495aff3ce945b38543 to your computer and use it in GitHub Desktop.
Save sgibb/6c95ea17296b68495aff3ce945b38543 to your computer and use it in GitHub Desktop.
s4 dispatching
bin <- function(x)x
setGeneric("bin", function(x) standardGeneric("bin"))
setMethod("bin", "matrix", function(x)x)
i <- 1:10
m <- matrix(1:10, nrow=2)
showMethods("bin")
# Function: bin (package .GlobalEnv)
# x="ANY"
# x="matrix"
bin2 <- function(x)x
f1 <- function(x) { for(i in x)bin(x) }
f2 <- function(x) { for(i in x)bin2(x) }
f3 <- function(x) { .bin <- selectMethod("bin", "ANY"); for(i in x).bin(x) }
x <- 1:1e5
library("microbenchmark")
options(digits=4)
microbenchmark(always=f1(x), never=f2(x), once=f3(x))
# Unit: milliseconds
# expr min lq mean median uq max neval
# always 91.89 99.10 106.79 100.23 115.85 146.54 100
# never 25.22 27.12 28.94 27.59 30.13 48.34 100
# once 24.30 25.89 27.37 26.14 28.61 36.89 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment