On Thu, Mar 27, 2014 at 12:43 PM, Artur T.
<artur.tarassow(a)googlemail.com> wrote:
Just out of curiosity: Does it make any difference, from a
computational
perspective, whether I choose option 1 or 2? In option 2 I concretely
pre-allocate memory, which should be more efficient, right?
<hansl>
#Opt 1:
matrix X = x1~x2~..~xp
#Opt 2:
matrix X = zeros(T,p)
X[,1] = x1
X[,2] = x2
...
X[,p] = xp
<\hansl>
I would expect option 2 to be more efficient for large matrices: it
should be less
time consuming to fill a pre-allocated matrix that to keep resizing a
matrix that
starts out dimensionless. But Sven is right (in his parallel reply) to
say that it's
an empirical matter.
Having done an experiment I'm actually quite surprised at just how much faster
option 2 is. Here's my test:
<hansl>
scalar p = 400
matrix xi = mnormal(T,1)
# option 1
set stopwatch
matrix X = {}
loop i=1..p -q
X ~= xi
endloop
printf "time1 = %g seconds\n", $stopwatch
# option 2
set stopwatch
matrix X = zeros(T,p)
loop i=1..p -q
X[,i] = xi
endloop
printf "time2 = %g seconds\n", $stopwatch
</hansl>
I've run this several times (and also with the order swapped) and I'm seeing
about 0.4 seconds for option 1 versus 0.007 seconds for option 2.
Allin Cottrell