MathGroup Archive 2008

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

Search the Archive

Re: Print[Plot] vs Print[text,Plot]? (*now Do and Table*)

On 4/25/08 at 5:29 AM, popkov at (Alexey Popkov) wrote:

>And I was surprised much more when I have tried the more simple form
>of the first expression:

>Timing[icount = 0;
>Do[icount += i, {i, 1, 10000000, 1}]; icount]
>(*this returns {36.042, 50000005000000} on my machine*)

>It means that using the "+=" operator takes about 50% more time than
>the usual form icount = icount + i; It is sad and very surprising!

I understand why you might consider this surprising if you come
from a C/C++ background. But why sad?

You simply need to realize Mathematica is not C/C++. What is
most efficient in such languages cannot be assumed to be most
efficient in Mathematica.

My experience indicates using Mathematica's functional
constructs (Map, Apply etc) are almost always faster than the
procedural constructs (Do, For etc.). Since I have no access to
the source code, I've no real idea why this is so. I simply
accept it as so and write code accordingly.

Another rule of thumb seems to be, things run faster when the
minimum amount of information needed is given rather than a more
complete specification. For example, on my machine:

In[251]:= Timing[Total@Table[n, {n, 1, 1000000, 1}]]

Out[251]= {1.2309,500000500000}

In[252]:= Timing[Total@Table[n, {n, 1, 1000000}]]

Out[252]= {1.16736,500000500000}

In[253]:= Timing[Total@Table[n, {n, 1000000}]]

Out[253]= {1.16389,500000500000}

There are other benefits to the functional style over the
procedural style in addition to performance. With C/C++ loops
probably one of the more common errors is to be one off at the
end of a loop. This could happen as a result of using say n <
limit versus n <= limit for the stopping criteria or failing to
have the stopping test in the right sequence with the step
incrementing the loop counter. These kind of problems are
eliminated with functional programming constructs since you
never need worry about the size on an array.

  • Prev by Date: Re: Wolfram User Interface Research? [off-topic!]
  • Next by Date: Re: Print[Plot] vs Print[text,Plot]?
  • Previous by thread: Re: Print[Plot] vs Print[text,Plot]? (*now Do and Table*)
  • Next by thread: Re: Re: Print[Plot] vs Print[text,Plot]? (*now Do and Table*)