<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/growing-objects-and-loop-memory-pre-allocation/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://insightr.wordpress.com/2018/08/23/growing-objects-and-loop-memory-pre-allocation/"> R â€“ insightR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<div><strong>By Thiago Milagres</strong></div>
</div>
<h2>Preallocating Memory</h2>
<p>This will be a short post about a simple, but very important concept that can drastically increase the speed of poorly written codes. It is very common to see R loops written as follows:</p>
<pre>v = NULL
n = 1e5
for(i in 1:n) v = c(v, i)
</pre>
<p>This seems like a natural way to write such a task: at each iteration, we increase our vector <em>v</em> to add one more element to it.</p>
<p><span></span></p>
<p>However, we will see that if we simply initialize a vector (with NAs, zeros or any other value) with the total length and then run the loop, we can drastically increase the speed of our algorithm. To illustrate this point, we will use the <em>microbenchmark</em> package. First, let’s put both approaches in functions:</p>
<pre>f_slow = function(n) {
  v = NULL
  for(i in 1:n) v = c(v, i)
  return(v)
}

f_fast = function(n) {
  v = rep(NA, n)
  for(i in 1:n) v[i] = i
  return(v)
}
</pre>
<p>Now to compare the speeds we can start with a small value of <em>n</em>, say 100.</p>
<pre>library(microbenchmark)
library(ggplot2)
n = 100
mbm = microbenchmark(&quot;f_slow&quot; = f_slow(n),
                      &quot;f_fast&quot; = f_fast(n), times = 50
                      )
print(mbm)
</pre>
<pre>## Unit: microseconds
##    expr    min     lq   mean median     uq      max neval
##  f_slow 24.060 24.576 64.690 25.156 26.892 1958.947    50
##  f_fast  5.098  5.419 43.235  5.562  5.790 1882.557    50
</pre>
<p>We see that even for such a simple loop, preallocating the vector already makes a big difference in the runtime. For bigger values of <em>n</em>, such difference becomes much more relevant:</p>
<pre>n = 1e5
mbm = microbenchmark(&quot;f_slow&quot; = f_slow(n),
                      &quot;f_fast&quot; = f_fast(n), times = 50
                      )
print(mbm)
</pre>
<pre>## Unit: milliseconds
##    expr      min       lq     mean   median       uq      max neval
##  f_slow 8615.797 8697.359 8736.413 8728.380 8776.894 8879.216    50
##  f_fast    4.683    4.968    5.257    5.100    5.196    7.098    50
</pre>
<p>Fully understanding why this happens would require understanding how dynamic allocation of memory works, which is not our focus here, but the basic idea is that when the object grows inside a loop, the computer must repeatedly find more space available for it in the memory, which is a costly process that can lead to memory fragmentation. For illustration purposes, let’s plot the object size (in bytes) as a function of <em>i</em> for our two loops. Note how, in the <em>fast</em> case, the object doesn’t increase in size over time.</p>
<pre>library(pryr)
n = 1e5
object_size_slow_loop = rep(NA, n)
object_size_fast_loop = rep(NA, n)

v1 = NULL
for(i in 1:n) {
  v1 = c(v1, i)
  object_size_slow_loop[i] = object_size(v1)
}

v2 = rep(NA, n)
for(i in 1:n){
  v2[i] = i
  object_size_fast_loop[i] = object_size(v2)
} 

sizes = cbind.data.frame(object_size_fast_loop, object_size_slow_loop)
print(ggplot(sizes, aes(1:n)) +
  geom_line(aes(y = object_size_fast_loop, colour = &quot;Fast loop&quot;)) +
  geom_line(aes(y = object_size_slow_loop, colour = &quot;Slow loop&quot;)) +
  ggtitle(&quot;Size of the object at each iteration&quot;) + xlab(&quot;Iteration&quot;) + ylab(&quot;Size in bytes&quot;)
)
</pre>
<p><img alt="plot of chunk plot_size" src="https://i2.wp.com/i.imgur.com/weFPMHx.png?w=456&ssl=1" data-recalc-dims="1"></p>
<h2>Beyond Vectors</h2>
<p>In the above examples, we used vectors just because they are simpler to visualize, but note that this principle holds for any other data structure, such as matrices and lists. Let’s see one quick example of each, starting with the matrix case:</p>
<pre>n = 1e3

f_slow_matrix = function(n) {
  M = NULL
  for(i in 1:n){
    M = rbind(M, rep(1, n))
  }
  return(M)
}

f_fast_matrix = function(n) {
  M = matrix(NA, nrow = n, ncol = n)
  for(i in 1:n){
    M[i,] = rep(1, n)
  }
  return(M)
}

mbmM = microbenchmark(&quot;f_slow_matrix&quot; = f_slow_matrix(n),
                      &quot;f_fast_matrix&quot; = f_fast_matrix(n)
                      ,times = 50
)
print(mbmM)
</pre>
<pre>## Unit: milliseconds
##           expr      min       lq     mean   median       uq       max neval
##  f_slow_matrix 5823.364 5858.490 5911.030 5914.014 5945.253  6040.606    50
##  f_fast_matrix    7.744    9.607   10.788   10.349   11.270    14.078    50
</pre>
<p>and, finally, an example with lists:</p>
<pre>n = 1e4

f_slow_list = function(n) {
  L = list()
  for(i in 1:n){
    L[[paste0('index_',i)]] = i
  }
  return(L)
}

f_fast_list = function(n) {
  L = vector(mode = &quot;list&quot;, length = n)
  for(i in 1:n){
    L[[i]] = i
  }
  names(L) = paste0(&quot;index_&quot;, 1:n)
  return(L)
}

mbmL = microbenchmark(&quot;f_slow_list&quot; = f_slow_list(n),
                      &quot;f_fast_list&quot; = f_fast_list(n)
                      ,times = 50
)
print(mbmL)
</pre>
<pre>## Unit: milliseconds
##         expr     min      lq    mean  median      uq      max neval
##  f_slow_list 607.299 616.947 682.738 639.575 656.597 1298.282    50
##  f_fast_list   3.273   3.364   3.967   3.559   3.775    7.704    50
</pre>
<h2>Final Note: When maximum length is not known from the start</h2>
<p>It could be the case that the maximum length is not known to the user. However, an upper bound (even a very bad one) could be used, and then after running the loop we can simply delete the part that wasn’t useful. For example, suppose that the true length is 100,000, but all we known is the upper bound 10,000,000. We can preallocate memory using our upper bound, as follows:</p>
<pre>n = 1e5
UB = 1e7
f_slow = function(n) {
  v = NULL
  for(i in 1:n) v = c(v, i)
  return(v)
}

f_fast_upper_bound = function(n, UB) {
  v = rep(NA, UB)
  for(i in 1:n) {
    v[i] = i
  }
  v = v[1:n]
  return(v)
}

mbmUB = microbenchmark(&quot;f_slow&quot; = f_slow(n),
                      &quot;f_fast_upper_bound&quot; = f_fast_upper_bound(n, 1e7), times = 50
                      )
print(mbmUB)
</pre>
<pre>## Unit: milliseconds
##                expr      min       lq     mean   median       uq      max neval
##              f_slow 7529.350 7903.024 8394.622 8598.460 8828.130 9318.457    50
##  f_fast_upper_bound   38.629   54.643  112.712   128.72  137.910  224.047    50
</pre>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://insightr.wordpress.com/2018/08/23/growing-objects-and-loop-memory-pre-allocation/"> R â€“ insightR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/SpouRBzPstU" height="1"></a></div>