       Re: ConstantArray and List

• To: mathgroup at smc.vnet.net
• Subject: [mg88184] Re: [mg88156] ConstantArray and List
• From: Carl Woll <carlw at wolfram.com>
• Date: Sun, 27 Apr 2008 05:00:19 -0400 (EDT)
• References: <200804260746.DAA08772@smc.vnet.net>

```Szabolcs Horvát wrote:

>Consider the following inputs:
>
>In:= ConstantArray[f[], {5}]
>
>Out= {f[], f[], f[], f[], f[]}
>
>In:= ConstantArray[List[], {5}]
>
>During evaluation of In:= ConstantArray::scalar: Argument {} at \
>position 1 is not a scalar. >>
>
>Out= ConstantArray[{}, {5}]
>
>
>Why doesn't the second one work?  Is this because of the way packed
>arrays are handled (just a guess)?
>
>
>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[]).
>
>
Try comparing ConstantArray and Table for the creation of very large
packed arrays:

In:= ConstantArray[0, 10^7]; // Timing
Table[0, {10^7}]; // Timing

Out= {0.031,Null}

Out= {0.531,Null}

In:= ConstantArray[1., {10^4, 10^3}]; // Timing
Table[1., {10^4}, {10^3}]; // Timing

Out= {0.062,Null}

Out= {0.531,Null}

So, ConstantArray is useful when you want to create a large constant
packed array, which you then modify in some way. This approach is very
common in Compile code.

Another example is:

In:= r1 = Table[ConstantArray[i, 10^6], {i, 10}]; // Timing
r2 = Table[i, {i, 10}, {10^6}]; // Timing
r1 === r2

Out= {1.84075*10^-13,Null}

Out= {1.844,Null}

Out= True

although here, I should mention that neither r1 nor r2 are packed.

Carl Woll
Wolfram Research

```

• Prev by Date: Re: Enable multicore calculation ?
• Next by Date: Re: ConstantArray and List
• Previous by thread: ConstantArray and List
• Next by thread: Re: ConstantArray and List