Many high-level programming languages allow their users to afford the luxury of extending an existing matrix or vector. The question is, how luxury it can be?

The two functions below both return an \(m \times n\) matrix, by calling a random generator \(n\) times. The first function does that by initializing the whole matrix with zeros, and filling the values until finish. The second extends the results one column at a time.

alloc_and_assign <- function(dimension) {
  m = matrix(rep(0,dimension[1]*dimension[2]), nrow=dimension[1])
  for (i in 1:ncol(m)) {
    m[,i] <- runif(dimension[1])
  }
}

create_and_extend <- function(dimension) {
  m = runif(dimension[1])
  for (i in 2:dimension[2]) {
    m = cbind(m, runif(dimension[1]))
  }
}

The performance of these two functions are starkly different when the number of columns increases.

So, the answer is, if you know the dimension of your result before hand, it’s always wise to allocate the whole block from the start.