repeat(lengthOf(list)) vs. forEach(item)In(list)

I was wondering which block was more optimal to use in a case where you want to iterate for a length of a list. For example:

Should you use something like this:

untitled script pic (1)

Or this:

untitled script pic (2)

I do not need to use the item variable in my loop. Is there an objectively better block or is to just personal preference? I am currently leaning towards repeat(lengthOf(list)) because it seems more straightforward to me, but I am open to suggestions. Thanks!

If you don’t need the contents of the list, it’s probably better to use repeat ([length V] of (list)) { } . If you want the indexes, you may want to use for ((i)) = (1) to ([length V] of (list)) { }

I don’t need the contents or the indexes of the list. Could you explain why repeat(lengthOf(list)) is better?

Both for (i) = () to () and for each (item) in () create variables which you don’t need for this situation. You might want a little bit of performance, even though the difference is not discernible.

Depending on how the list was created, Snap! probably knows the length of the list without walking through each item. But any efficiency difference will be small, because you want to repeat the DOsOMETHING that many times anyway. If you’re really worried about running time, see if you can find a way to avoid the repetition altogether. For a simple example of what I mean, instead of


you could say
untitled script pic (8)

So, to be clear, repeat(lengthOf(list)) is more performant?

I don’t think avoiding repetition will make sense in my case, but that is an interesting way to go about it. Thanks for the reply.

could we see your example?(project link)

In terms of the control structure itself: repeat vs for vs for each do not have any meaningful differences in performance. Whether or not an additional variable is created to reference each item or an index won’t affect anything.

what’s best depends on your use, but in this case we would generally say less is more. If you don’t need an index you should use a basic repeat loop because it avoids the question of “why wasn’t an index used”.

code is read way more often than it is written. Clarity is always a valid goal.

Understood. Thank you!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.