Advanced Programming and Performance Tuning

Article · 3:00

R's three object systems, the metaprogramming that makes dplyr possible, and making slow code fast in the right order.

R has three object systems, which sounds like a mess and is mostly a history lesson with practical consequences.

S3 is informal and is what you will meet everywhere. An object is given a class attribute, and print.myclass() is found by print() through naming convention alone. There is no checking: you can set any class on anything. It is what lm(), data.frame and nearly all of base R use, and for most purposes it is enough.

S4 is formal: slots with declared types, validity functions, and multiple dispatch on several arguments at once. It is verbose, and it is used where correctness matters more than convenience - Bioconductor is built on it.

R6 gives you what programmers arriving from Python or Java expect: reference semantics and mutable state. Where S3 and S4 objects are copied on modification, an R6 object is modified in place. That makes it right for things that genuinely are stateful - a database connection, a counter, a Shiny module - and wrong for data, where R's copy-on-modify is a feature that stops action at a distance.

Non-standard evaluation is how filter(df, x > 5) works without x existing as a variable. The function receives the unevaluated expression and chooses where to evaluate it - inside the data frame. That is what makes the tidyverse read as it does. The cost is that writing your own function wrapping a dplyr verb does not work naively, because your parameter name gets used literally. The fix is {{ }} - "embrace" the argument - from rlang. For a column name held in a string, .data[[name]].

Performance has an order, and skipping to the end is the usual mistake.

  1. Profile first. profvis() shows where the time actually goes, and it is routinely somewhere you did not expect. Optimising by intuition is optimising the wrong line.
  2. Vectorize. Replacing an explicit loop with a vectorized operation is often a 10-100x win, because the loop then runs in compiled C instead of in R.
  3. Pre-allocate. Growing a vector with c() in a loop copies the whole thing every iteration, making a linear algorithm quadratic.
  4. Use the right tool. data.table is dramatically faster than dplyr on large data; collapse is faster still for grouped statistics; matrix operations beat data frames when everything is numeric.
  5. Then consider Rcpp. Dropping to C++ gives 50-100x on genuinely iterative work that cannot be vectorized - recursive algorithms, simulations with sequential dependence. It is the last resort, not the first, because it costs you a compiler and a second language.
library(R6)
library(rlang)
library(dplyr)

# ---- S3: a class attribute and a naming convention ------------------
account <- structure(list(owner = "Ada", balance = 100), class = "account")

print.account <- function(x, ...) {          # name.class - that is all
  cat("Account:", x$owner, "balance", x$balance, "\n")
  invisible(x)
}
print(account)        # print() dispatches on class(x) and finds this

# No checking of any kind:
class(42) <- "account"        # legal. There are no slots to be wrong.

# ---- S4: declared slots, checked -------------------------------------
setClass("Account", representation(owner = "character", balance = "numeric"),
         validity = function(object) {
           if (object@balance < 0) "balance cannot be negative" else TRUE
         })
setGeneric("deposit", function(acc, amount) standardGeneric("deposit"))
setMethod("deposit", "Account", function(acc, amount) {
  acc@balance <- acc@balance + amount
  acc                                  # returns a COPY, like S3
})

a <- new("Account", owner = "Grace", balance = 50)
a <- deposit(a, 25)                    # reassignment required
# new("Account", owner = "x", balance = -1)   # error: validity fails

# ---- R6: reference semantics, mutable in place ----------------------
Counter <- R6Class("Counter",
  public = list(
    count = 0,
    initialize = function(start = 0) { self$count <- start },
    add = function(n = 1) {
      self$count <- self$count + n
      invisible(self)                  # invisible(self) makes it chain
    }
  )
)

c1 <- Counter$new()
c1$add()$add()$add(5)
c1$count                               # 8 - modified IN PLACE

c2 <- c1                               # NOT a copy. Same object.
c2$add()
c1$count                               # 9 - c1 changed too.
#
# That is the whole difference, and why R6 is right for a connection or
# a Shiny module and wrong for data. R's copy-on-modify is what stops
# one function quietly changing another's data.

# ---- NSE: why filter(df, x > 5) works -------------------------------
# This does NOT work. `col` is used literally as a column name.
broken <- function(data, col) {
  data |> summarise(avg = mean(col))
}

# {{ }} - "embrace" - passes the expression through:
average_of <- function(data, col) {
  data |> summarise(avg = mean({{ col }}, na.rm = TRUE))
}
average_of(mtcars, mpg)                # works

# A column name held in a STRING uses .data instead:
average_named <- function(data, name) {
  data |> summarise(avg = mean(.data[[name]], na.rm = TRUE))
}
average_named(mtcars, "mpg")

# ---- Performance, in the order that pays -----------------------------

# 1. PROFILE. Do not guess.
#    profvis::profvis({ your_slow_code() })

# 2. VECTORIZE - usually the biggest single win.
x <- runif(1e6)

# slow: a million R-level iterations
out <- numeric(length(x))
for (i in seq_along(x)) out[i] <- x[i] * 2

out <- x * 2        # fast: one call, the loop runs in compiled C

# 3. PRE-ALLOCATE when a loop is genuinely needed.
#    result <- c()                     quadratic: copies every time
#    result <- numeric(n)              linear

# 4. THE RIGHT TOOL at size.
#    data.table::setDT(df)[, .(m = mean(v)), by = g]   # fast at scale
#    collapse::fmean(df$v, g = df$g)                   # faster still

# 5. Rcpp, LAST, for work that cannot be vectorized.
#
#    Rcpp::cppFunction('
#      double sum_cpp(NumericVector x) {
#        double total = 0;
#        for (int i = 0; i < x.size(); ++i) total += x[i];
#        return total;
#      }')
#
#    50-100x on sequential algorithms - recursion, simulations where
#    each step depends on the last. It costs you a compiler and a
#    second language, which is why it is step five and not step one.

# Measuring properly - bench::mark checks the results MATCH as well as
# timing them, which stops you "optimising" into a different answer:
#   bench::mark(loop = { ... }, vectorized = { ... })

Discussion

No questions on this topic yet. Sign in to ask the first one.