four approaches to do a simple sum

*To*: mathgroup at smc.vnet.net*Subject*: [mg57171] four approaches to do a simple sum*From*: Hui Fang <fangh73 at xmu.edu.cn>*Date*: Fri, 20 May 2005 04:43:04 -0400 (EDT)*Organization*: Xiamen University Photonics Center*Reply-to*: fangh73 at xmu.edu.cn*Sender*: owner-wri-mathgroup at wolfram.com

Here I have a long list, length of 1 million, and I used 4 ways to get the sum of all elements. In[1] = longlist=Table[Random[], {1000000}]; Method 1: In[2] = Timing[sum=0; For[i=1,i<=Length[longlist],sum+=longlist[[i]]]; sum] Out[2] = {6.219 Second, 500358} Method 2: In[3] = Sum[longlist[[i]],{i,1,1000000}] Out[3] = {1.718 Second, 500358} Method 3: In[4] = Timing[Plus@@longlist] Out[4] = {0.407 Second, 500358} Method 4: In[5] = Fold[Plus,0,longlist] Out[5] = {0.156 Second, 500358} The computing time gets shorter and shorter from top to bottom. It's easy to understand why the first two methods are slow because they involved an extra variable i for loop control and basically violates the principle for list manipulation "Never take a list apart". What I don't understand is why method 4 is faster than method 3. Any explanation?Or do you have an even faster method? Thanks a lot! Hui Fang

**Follow-Ups**:**Re: four approaches to do a simple sum***From:*Daniel Lichtblau <danl@wolfram.com>

**Re: four approaches to do a simple sum***From:*Andrzej Kozlowski <akoz@mimuw.edu.pl>