MathGroup Archive 2002

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: AppendTo VERY slow

  • To: mathgroup at smc.vnet.net
  • Subject: [mg35323] Re: [mg35279] AppendTo VERY slow
  • From: Andrzej Kozlowski <andrzej at platon.c.u-tokyo.ac.jp>
  • Date: Mon, 8 Jul 2002 03:17:36 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

The answer is to learn to program in "Mathematica style", which 
manipulates lists as wholes and in particular avoids commands that force 
them to be re-computed. Append is one of these commands to be avoided. 
Compare the timings of the following two programs:

In[2]:=
n=1000;xlist=Table[Random[],{n}];ylist=Table[Random[],{n}];outlist={};

your version:

In[3]:=
Do[ elem = {xlist[[count]], ylist[[count]]};
     	AppendTo[outlist, elem];
      , {count, 1, n}
     ];//Timing

Out[3]=
{0.42 Second,Null}

The  "Mathematica style" approach:

In[4]:=
s=Transpose[{xlist,ylist}];//Timing

Out[4]=
{0. Second,Null}

In[5]:=
s==outlist

Out[5]=
True

Andrzej Kozlowski
Toyama International University
JAPAN
http://platon.c.u-tokyo.ac.jp/andrzej/


On Saturday, July 6, 2002, at 06:44  PM, Mike wrote:

> I use lists a lot in mathematica and tend to use AppendTo[] a lot in
> my programs.  Recently I wrote a function that i call over and over
> again and found that the results were coming very slowly and i MEAN
> slowly.  I was doing Fourier Transforms and all kinds of stuff so I
> put it down to those at first but I have just put in a load of Print
> statements just after each part of the function to see what was taking
> so long.
>
> I was amazed to see that the Fourier Transforms were so quick and what
> was actually taking the time was a part of my function that collected
> the results togther in the form I wanted and outputted the result.  It
> looks like this
>
> Do[
>     	elem = {xlist[[count]], ylist[[count]]]};
>     	AppendTo[outlist, elem];
>      , {count, 1, number}
>     ];
>
> It seems that as the list grows it gets slower and slower.  Any tips
> on a way around this would be greatly appreciated (would speed my life
> up no end)
>
>
> Thank
>
> Mike
>
>
>



  • Prev by Date: RE: A Bug?
  • Next by Date: Re: AppendTo VERY slow
  • Previous by thread: Re: AppendTo VERY slow
  • Next by thread: Re: AppendTo VERY slow