Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Yes, `Table` is always faster than `list = {}; Do[AppendTo[list, ...], ...]`.
- The reason is that `AppendTo` is forced to re-allocate the memory used to store the array `list` in order to make room for one more element, and then copy the existing contents to the new memory location. This means that the time it takes `AppendTo[list, element]` to execute is proportional to the length of `list`. Thus `Do[AppendTo[list, i], {i, n}]` will take time proportional to `n^2` to execute.
- `Table[i, {i, n}]` knows the length of the list it needs to generate in advance, thus it only needs to allocate memory once. It runs in time proportional to `n`.
- For large enough `n`, `c1*n^2 > c2*n`. In the example above the proportionality constants `c1` and `c2` are likely very close to each other, which is why I stated that `Table` is *always* faster.
- In some situations however, you either don't want to store all results computed in a `Do` loop or you don't know how many iterations you are going to perform before you stop looping. In these cases you can use [`Sow`](http://reference.wolfram.com/mathematica/ref/Sow.html)/[`Reap`](http://reference.wolfram.com/mathematica/ref/Reap.html) to achieve better than $O(n^2)$ performance.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement