title: Calculating the mean within a loop reduces performance
body: <p>Consider the first example:
  It calculates mean within the loop. </p>
  
  <pre><code>st &lt;- Sys.time() #Starting Time 
  set.seed(123456789)
  vara &lt;- c()
  sda &lt;- c()
  mvara &lt;- c() #store mean
  msda &lt;- c() #store mean of standard deviation
  
  K &lt;- 100000
  
  for(i in 1:K) {
    a &lt;- rnorm(30)
    vara[i] &lt;- var(a)
    sda[i] &lt;- sd(a)
    mvara[i] &lt;- mean(mvara)
    msda[i] &lt;- mean(msda)
  }
  
  et &lt;- Sys.time()
  
  et-st  #time taken by code (approx more than one minute)
  </code></pre>
  
  <p>Consider the same code, except that the same mean is calculated outside the loop. </p>
  
  <pre><code>st &lt;- Sys.time() #Starting Time 
  set.seed(123456789)
  vara &lt;- c()
  sda &lt;- c()
  
  K &lt;- 100000
  
  for(i in 1:K) {
    a &lt;- rnorm(30)
    vara[i] &lt;- var(a)
    sda[i] &lt;- sd(a)
  }
  
  mvara &lt;- cumsum(vara)/ (1:K)
  msd &lt;- cumsum(sda)/ (1:K)
  et &lt;- Sys.time()  #less than 5 seconds
  </code></pre>
  
  <p>I just wanted to know, why there is so much difference in performance of both the codes? Where one should take care when using loop? </p>