Read Online
Download PDF
Additional resources
Revision history
Known typos/bugs
Report a bug
License terms
About the author
"node298_1.gif" "node298_2.gif" "node298_3.gif"     Efficiency pitfall: constructing a list with Append

Let us compare the elapsed time of such list generation with that of Range, using the function myTiming :

Check now:





We see that constructing a list of  (symbolic) values of Sin on a thousand first natural numbers is hundred times slower with Append than with Range. But the truth is that the computational complexities are different and the larger is the list, the more overhead is induced by using Append. We can also see how Table will perform:



We see that it is a little slower than Range.

In addition to being slower, the generation with the loop introduced a global side effect  - the variable <testlist>. So, to make the code clean, one will have in this approach to wrap the loop in an additional modularization construct and thus make it even clumsier.

So, in conclusion, I would thoroughly discourage the reader from straightforward list generation inside a loop.  First,  there are almost always better design solutions which avoid this problem altogether. Second,  there exist  workarounds  to get a linear time performance in doing it, such as using linked lists (to be discussed below), or indexed variables. Finally, starting with version 5, there are special commands Reap and Sow introduced specifically for efficient generation and collection of intermediate results in computations - we will have an entire chapter in the part II devoted to these commands.

"node298_10.gif" "node298_11.gif" "node298_12.gif"

Created by Wolfram Mathematica 6.0  (05 February 2009) Valid XHTML 1.1!