LIST procesing

As I was working with microBlocks (of John Maloney), I came to realize that list handling performance was very different if one declares a list and ADDs N elements to it, versus declares a list with N elements and then REPLACES these elements with the proper values. The REPLACE always worked magnitudes faster.

I tested the same logic in SNAP and saw that there was a totally reverse time difference between the two approaches.

ADD of 100 list elements took consistently LESS than 3ms to process.
REPLACE of 100 elements took consistently 4-13ms to process.

Here are the two code blocks compared:

Any reason for the opposite behaviour and why SNAP is so much better at handling element ADDs ?

Just curious !

PS: When I tried the REPLACE within a FOR i 1 TO 100 loop, it also went down to 1-3ms.


That # FOR EACH... block is written in Snap! and is therefore slower than FOR, which is written in Javascript. If you use the regular FOR EACH and keep an index count separately it'll be faster.

Jens had a good suggestion:

It's a little kludgy, but we don't have the value-index-list feature for FOR EACH.

Cool. I'll put that method in my tools list.

One last related question:
Is it any faster to process a list element via a variable where "variable = item n of list" versus directly using "item n of list", if "item n of list" is repeated many times in a loop ?
Since the first method is a bit faster with calculations, I was wondering if the same logic applies to lists ?

I'm afraid the answer is "it depends." If you are doing functional programming, with lots of IN FRONT OF to construct lists, then ITEM n OF for large n is slow. (Other things are fast; it's a tradeoff.) If you're doing imperative programming, with lots of ADD value TO list, then ITEM OF is constant time and it shouldn't make much difference either way.