Re: AppendTo VERY slow

• To: mathgroup at smc.vnet.net
• Subject: [mg35310] Re: [mg35279] AppendTo VERY slow
• From: Rob Pratt <rpratt at email.unc.edu>
• Date: Mon, 8 Jul 2002 03:15:49 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```On Sat, 6 Jul 2002, 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

You can use lis = Join[lis, {elem}] as a general workaround to
AppendTo[lis, elem].  It might also speed things up to get rid of the Do.
Assuming number is the common length of xlist and ylist, the following
should do the job:

xylist = Transpose[{xlist, ylist}];

Map[(outlist = Join[outlist, {#}])&, xylist];

If number is smaller than the length of xylist, you can replace the first
line with:

xylist = Take[Transpose[{xlist, ylist}], number];

More generally, if xlist and ylist have different lengths, use:

xylist = Transpose[{Take[xlist, number], Take[ylist, number]}];

Rob Pratt
Department of Operations Research
The University of North Carolina at Chapel Hill

rpratt at email.unc.edu

http://www.unc.edu/~rpratt/

```

• Prev by Date: Re: AppendTo VERY slow
• Next by Date: Strategy for overly long computations?
• Previous by thread: Re: AppendTo VERY slow
• Next by thread: RE: AppendTo VERY slow