Re: ConstantArray and List
- To: mathgroup at smc.vnet.net
- Subject: [mg88168] Re: ConstantArray and List
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sun, 27 Apr 2008 04:57:22 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <fuumjj$8i2$1@smc.vnet.net>
� wrote:
> Consider the following inputs:
>
> In[1]:= ConstantArray[f[], {5}]
>
> Out[1]= {f[], f[], f[], f[], f[]}
>
> In[2]:= ConstantArray[List[], {5}]
>
> During evaluation of In[2]:= ConstantArray::scalar: Argument {} at \
> position 1 is not a scalar. >>
>
> Out[2]= ConstantArray[{}, {5}]
>
>
> Why doesn't the second one work? Is this because of the way packed
> arrays are handled (just a guess)?
Packed array occurs, if I remember correctly, when the array has more
than 250 or more elements.
> What is the advantage of ConstantArray over Table or Array? It doesn't
> seem to be much faster, and it doesn't seem to return an array stored in
> a more efficient way (I experimented a little with MemoryInUse[]).
The difference is the building speed of an array for ConstantArray
evaluates only once the expression that is going to be present in every
entry while Array evaluates the expression for each elements. In the
examples below, we can see that building an array of symbols is five
times faster, an array of constant integers is up to 30 times faster.
In[22]:= ConstantArray[f[], {5000, 5000}] // Timing // First
Out[22]= 2.10453
In[23]:= Array[f[], {5000, 5000}] // Timing // First
Out[23]= 9.36111
In[24]:= %/%%
Out[24]= 4.44809
In[25]:= ConstantArray[1, {5000, 5000}] // Timing // First
Out[25]= 0.140288
In[26]:= Array[1, {5000, 5000}] // Timing // First
Out[26]= 4.07251
In[27]:= %/%%
Out[27]= 29.0296
In[28]:= ConstantArray[1., {5000, 5000}] // Timing // First
Out[28]= 0.253713
In[29]:= Array[1., {5000, 5000}] // Timing // First
Out[29]= 4.04874
In[30]:= %/%%
Out[30]= 15.9579
Best regards,
-- Jean-Marc