Re: Another AppendTo replacement problem
- To: mathgroup at smc.vnet.net
- Subject: [mg118258] Re: Another AppendTo replacement problem
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Mon, 18 Apr 2011 06:50:13 -0400 (EDT)
On 4/17/11 at 7:16 PM, koopman at sfu.ca (Ray Koopman) wrote:
>On Apr 17, 4:51 am, "Sjoerd C. de Vries"
><sjoerd.c.devr... at gmail.com> wrote:
>>The usual trick is to replace AppendTo[list,elem] with list
>>{list,elem}.
>See Maxim Rytin, "Two heads are better than one",
>http://forums.wolfram.com/mathgroup/archive/2006/May/msg00175.html
>The trick he suggests builds just as fast as, and unravels twice as
>fast as, the usual trick.
>Timing[s = {}; Do[s = {s, h[i,-i] }, {i,1*^6}]; Length@s]
>Timing[Length[ss = Flatten@s /. h->List]]
>{4.23 Second,2} {1.82 Second,1000000}
>Timing[z = h[]; Do[z = h[z, {i,-i} ], {i,1*^6}]; Length@z]
>Timing[Length[zz = List @@ Flatten[z,Infinity,h]]]
>{4.25 Second,2} {0.71 Second,1000000}
>zz === ss
>True
The results I get indicate simply using nested lists then using
Partition to reconstruct the array appropriately is faster. That is:
In[1]:= Timing[z = h[]; Do[z = h[z, {i, -i}], {i, 1*^6}]; Length@z]
Timing[Length[zz = List @@ Flatten[z, Infinity, h]]]
Out[1]= {1.6739,2}
Out[2]= {0.622828,1000000}
In[3]:= Timing[s = {}; Do[s = {s, {i, -i}}, {i, 1*^6}]; Length@z]
Timing[Length[ss = Partition[Flatten[s], Length[Last@s]]]]
Out[3]= {1.61893,2}
Out[4]= {0.392044,1000000}
In[5]:= ss == zz
Out[5]= True